温馨提示×

pyqt主窗口怎么创建子窗口

小亿
169
2023-11-18 12:10:51
栏目: 编程语言

在PyQt中,可以使用QMainWindow类作为主窗口,可以使用QWidget类作为子窗口。

以下是一个创建主窗口和子窗口的示例代码:

from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout, QPushButton

class ChildWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Child Window')
        self.setGeometry(100, 100, 300, 200)

        layout = QVBoxLayout()
        button = QPushButton('Close')
        button.clicked.connect(self.close)
        layout.addWidget(button)

        self.setLayout(layout)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Main Window')
        self.setGeometry(100, 100, 500, 400)

        self.child_window = ChildWindow()
        self.setCentralWidget(self.child_window)

if __name__ == '__main__':
    app = QApplication([])
    main_window = MainWindow()
    main_window.show()
    app.exec()

在上述代码中,我们创建了一个ChildWindow类作为子窗口,其继承自QWidget类。在ChildWindow的构造函数中,我们设置了子窗口的标题、大小和布局,并添加了一个按钮。在按钮的clicked信号与self.close槽函数之间建立了连接。

然后,我们创建了一个MainWindow类作为主窗口,其继承自QMainWindow类。在MainWindow的构造函数中,我们设置了主窗口的标题、大小,并创建了一个ChildWindow对象作为主窗口的中央窗口,通过self.setCentralWidget方法将其设置为中央窗口。

最后,我们创建了一个QApplication对象,实例化MainWindow对象,并通过show方法显示主窗口,最后通过app.exec方法进入主事件循环。

0