求助PyQt6
  • 板块学术版
  • 楼主zengyukai2012
  • 当前回复0
  • 已保存回复0
  • 发布时间2024/10/24 21:31
  • 上次更新2024/10/24 21:39:37
查看原帖
求助PyQt6
1090444
zengyukai2012楼主2024/10/24 21:31
import sys


from PyQt6.QtWidgets import (
    QApplication,
    QWidget,
    QLabel,
    QPushButton,
    QVBoxLayout,
    QMessageBox,
)
from PyQt6.QtCore import Qt


class TestInterface(QWidget):
    """测试界面的类"""
    
    def __init__(self) -> None:
        """初始化测试界面,设置窗口标题和固定尺寸"""
        super().__init__()

        self.setWindowTitle("Test")
        self.setFixedSize(300, 200)

        self.initUI()

    def initUI(self) -> None:
        """初始化用户界面,添加按钮并连接信号"""
        super().__init__()
        layout: QVBoxLayout = QVBoxLayout()

        login_button: QPushButton = QPushButton("show info")
        login_button.clicked.connect(self.show_info)  # type: ignore
        layout.addWidget(login_button)

        self.setLayout(layout)

    def show_info(self) -> None:
        """显示用户信息窗口并添加文本"""
        self.user_info_widget: QWidget = QWidget(self)
        self.user_info_widget.setWindowFlags(Qt.WindowType.Window)
        layout: QVBoxLayout = QVBoxLayout(self.user_info_widget)

        self.add_text("text")
        # 更新布局,确保控件被添加
        self.user_info_widget.update()

        # 调试信息
        for i in range(layout.count()):
            widget = layout.itemAt(i).widget()  # type: ignore
            if widget is not None:
                print(f"控件 {i}: {widget}")
            else:
                print(f"控件 {i}: None")

        self.user_info_widget.show()

    def add_text(self, text: str) -> None:
        """向用户信息窗口添加文本标签"""
        text_lable: QLabel = QLabel(text, self)
        text_lable.setStyleSheet("font-size: 16px;")
        temp_layout = self.user_info_widget.layout()
        if temp_layout:
            temp_layout.addWidget(text_lable)
            temp_layout.update()
            QMessageBox.information(self, "提示", "成功")
        else:
            self.show_error("错误:布局为空")

    def show_error(self, message: str) -> None:
        """显示错误消息框"""
        QMessageBox.critical(self, "错误", message)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    test_interface = TestInterface()
    test_interface.show()
    sys.exit(app.exec())

总是提示“错误:布局为空”

2024/10/24 21:31
加载中...