PyQT:在第一个窗口之前退出/完成第二个窗口

时间:2019-02-26 16:43:42

标签: python pyqt pyqt4

我在下面有以下代码:

from PyQt4 import QtGui
import sys


class Second(QtGui.QWidget):

    def __init__(self, parent=None):
        super(Second, self).__init__(parent)

        self.grid = QtGui.QGridLayout(self)
        self.setGeometry(650,400,400,200)
        self.widget = QtGui.QWidget()


class First(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(First, self).__init__(parent)

        self.grid = QtGui.QGridLayout(self)
        self.setGeometry(350, 200, 1000, 700)
        self.widget = QtGui.QWidget()

        Button1 = QtGui.QPushButton('...', self)
        Button1.clicked.connect(self.on_pushButton_clicked)
        self.grid.addWidget(Button1, 0, 0, 1, 1)


    def on_pushButton_clicked(self):
        self.Second = Second()
        self.Second.setWindowTitle('Window')
        self.Second.show()


def main():
    app = QtGui.QApplication(sys.argv)
    main = First()
    main.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

当我单击按钮时,我希望能够在第二个窗口中完成操作,然后再继续第一个窗口。现在,我可以退出第一个窗口,第二个窗口保持打开状态。您如何保留第二个窗口,但保持第一个窗口不可选择?

1 个答案:

答案 0 :(得分:1)

有2种可能的解决方案:

-第二个必须继承自QDialog,将其作为父级传递给第一个窗口,并使用exec_()代替show:

class Second(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Second, self).__init__(parent)

class First(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(First, self).__init__(parent)        
        self.setGeometry(350, 200, 1000, 700)
        self.widget = QtGui.QWidget()
        self.setCentralWidget(self.widget)
        grid = QtGui.QGridLayout(self.widget)
        Button1 = QtGui.QPushButton('...', self)
        Button1.clicked.connect(self.on_pushButton_clicked)
        grid.addWidget(Button1, 0, 0, 1, 1)

    @QtCore.pyqtSlot()
    def on_pushButton_clicked(self):
        self.Second = Second(self)
        self.Second.setWindowTitle('Window')
        self.Second.exec_()

-将windowModality更改为Qt::WindowModal,激活标志Qt::Dialog并将其作为父窗口传递给第一个窗口。

class Second(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Second, self).__init__(parent)
        self.setWindowModality(QtCore.Qt.WindowModal)
        self.setWindowFlags(self.windowFlags() | QtCore.Qt.Dialog)

class First(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(First, self).__init__(parent)        
        self.setGeometry(350, 200, 1000, 700)
        self.widget = QtGui.QWidget()
        self.setCentralWidget(self.widget)
        grid = QtGui.QGridLayout(self.widget)
        Button1 = QtGui.QPushButton('...', self)
        Button1.clicked.connect(self.on_pushButton_clicked)
        grid.addWidget(Button1, 0, 0, 1, 1)

    @QtCore.pyqtSlot()
    def on_pushButton_clicked(self):
        self.Second = Second(self)
        self.Second.setWindowTitle('Window')
        self.Second.show()