在PyQt5中,我想知道为什么隐藏QMainWindow会影响子对话框的行为?
例如,在下面的代码中,如果我点击"显示对话框"→"ok",显示QMessageBox,然后程序终止。但是,如果我注释掉showChildDialog()中的self.hide()和self.show(),程序将在显示QMessageBox之后返回显示子对话框。
理想情况下,我希望程序在显示QMessageBox后返回到子对话框,但我也希望在显示子对话框时隐藏主窗口。
如何同时实现这两种行为?
from PyQt5 import QtWidgets
class mainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(mainWindow, self).__init__(parent)
self.dialog = childDialog(self)
self.setWindowTitle('Main Window')
self.buttonShow = QtWidgets.QPushButton(self)
self.buttonShow.setText("Show Dialog")
self.buttonShow.clicked.connect(self.showChildDialog)
def showChildDialog(self):
self.hide() # works as intended if this commented out...
self.dialog.exec()
self.show() # and this.
class childDialog(QtWidgets.QDialog):
def __init__(self, parent=None):
super(childDialog, self).__init__(parent)
self.buttonOk = QtWidgets.QPushButton(self)
self.buttonOk.setText("OK")
self.buttonOk.clicked.connect(self.ok_clicked)
self.buttonHide = QtWidgets.QPushButton(self)
self.buttonHide.setText("Close")
self.buttonHide.clicked.connect(self.hide_clicked)
self.layout = QtWidgets.QVBoxLayout(self)
self.layout.addWidget(self.buttonOk)
self.layout.addWidget(self.buttonHide)
def hide_clicked(self):
self.accept()
def ok_clicked(self):
# do somehting here that causes an error
dialog = QtWidgets.QMessageBox(text='an error occurred')
dialog.exec()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
app.setApplicationName('myWindow')
main = mainWindow()
main.show()
sys.exit(app.exec_())
如果你改变这一行:
self.dialog = childDialog(self)
到这行:
self.dialog = childDialog()
工作正常