【问题标题】:How to call one mainwindow to another mainwindow in Qt (or PyQt)如何在 Qt(或 PyQt)中将一个主窗口调用到另一个主窗口
【发布时间】:2011-04-12 05:34:54
【问题描述】:

在我的项目中,我创建了两个主窗口,我想从 mainwindow1(正在运行)调用 mainwindow2。在 mainwindow1 中我已经使用了 app.exec_() (PyQt) 并显示 maindow2 我在按钮的单击事件中使用 maindow2.show() 但不显示任何内容

【问题讨论】:

    标签: qt4 pyqt4 qmainwindow


    【解决方案1】:

    调用 mainwindow2.show() 应该适合你。您能否提供更完整的代码示例?其他地方可能有问题。

    编辑: 更新代码以显示如何在打开和关闭其他窗口时隐藏和显示窗口的示例。

    from PyQt4.QtGui import QApplication, QMainWindow, QPushButton, \
                QLabel, QVBoxLayout, QWidget
    from PyQt4.QtCore import pyqtSignal
    
    class MainWindow1(QMainWindow):
        def __init__(self, parent=None):
            QMainWindow.__init__(self, parent) 
            button = QPushButton('Test')
            button.clicked.connect(self.newWindow)
            label = QLabel('MainWindow1')
    
            centralWidget = QWidget()
            vbox = QVBoxLayout(centralWidget)
            vbox.addWidget(label)
            vbox.addWidget(button)
            self.setCentralWidget(centralWidget)
    
        def newWindow(self):
            self.mainwindow2 = MainWindow2(self)
            self.mainwindow2.closed.connect(self.show)
            self.mainwindow2.show()
            self.hide()
    
    class MainWindow2(QMainWindow):
    
        # QMainWindow doesn't have a closed signal, so we'll make one.
        closed = pyqtSignal()
    
        def __init__(self, parent=None):
            QMainWindow.__init__(self, parent)
            self.parent = parent
            label = QLabel('MainWindow2', self)
    
        def closeEvent(self, event):
            self.closed.emit()
            event.accept()
    
    def startmain():
        app = QApplication(sys.argv)
        mainwindow1 = MainWindow1()
        mainwindow1.show()
        sys.exit(app.exec_())
    
    if __name__ == "__main__":
        import sys
        startmain()
    

    【讨论】:

    • 感谢灰色终于完成了。但我想让window1禁用并启用window2,当window2关闭时window1变为renable
    • 我更改了代码,以便在显示第二个 QMainWindow 时隐藏第一个。当第二个 QMainWindow 关闭时,第一个将再次显示。
    • 非常感谢您为@GaryHughes 编写代码,我为此苦苦挣扎。我的错误是我没有将第一个屏幕发送到第二个屏幕。你能解释一下为什么我们需要 QMainWindow.__init__(self, parent) send parent吗?在第一个和第二个窗口之间建立连接是有道理的,但我不能完全理解为什么我们需要将父级发送到超级构造函数中。再次非常感谢
    猜你喜欢
    • 2010-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-02
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多