当我点击按钮时,"ChildWindow"将闪烁并消失。然后,如果我添加函数exec_(),它将报告一个"AttributeError",因为"QMainWindow"没有这个属性。如何修改函数"showChildWindow"使其能够正常工作?非常感谢。
import sys
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setWindowTitle("MainWindow Window!")
self.setGeometry(400, 400, 100, 100)
self.centerWidget = QtGui.QWidget()
self.setCentralWidget(self.centerWidget)
self.pushButton = QtGui.QPushButton("&Button")
layout = QtGui.QVBoxLayout()
layout.addWidget(self.pushButton)
self.centerWidget.setLayout(layout)
class ChildWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setWindowTitle("Child Window!")
def showChildWindow():
mw = MainWindow()
child_win = ChildWindow(mw)
child_win.show()
#child_win.exec_() #AttributeError: 'ChildWindow' object has no attribute 'exec_'
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MainWindow()
myapp.show()
QtCore.QObject.connect(myapp.pushButton,QtCore.SIGNAL("clicked()"),showChildWindow)
sys.exit(app.exec_())
这个程序可以很好地运行。
import sys
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setWindowTitle("MainWindow Window!")
self.setGeometry(400, 400, 100, 100)
self.centerWidget = QtGui.QWidget()
self.setCentralWidget(self.centerWidget)
pushButton = QtGui.QPushButton("&Button")
layout = QtGui.QVBoxLayout()
layout.addWidget(pushButton)
self.centerWidget.setLayout(layout)
QtCore.QObject.connect(pushButton,QtCore.SIGNAL("clicked()"),self.showChildWindow)
def showChildWindow(self):
self.child_win = ChildWindow(self)
self.child_win.show()
class ChildWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setWindowTitle("Child Window!")
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = MainWindow()
myapp.show()
sys.exit(app.exec_())
真正的问题似乎是:如何从应用程序中的其他模块访问主窗口?
对于这个问题,我更喜欢的通用解决方案是对QApplication进行子类,并添加一个简单的访问器方法,如下所示:
class Application(QtGui.QApplication):
def __init__(self):
QtGui.QApplication.__init__(self, sys.argv)
self._window = None
def window(self):
if self._window is None:
self._window = MainWindow()
return self._window
if __name__ == "__main__":
app = QtGui.qApp = Application()
app.window().show()
sys.exit(app.exec_())
有了它,你可以很容易地访问其他模块中主窗口的方法,比如:
from PyQt4 import QtGui
QtGui.qApp.window().showChildWindow()
我也遇到了同样的问题。子QMainWindow在与父窗口交互时会随机消失。
这是导致此问题的错误源代码:
def showChildWindow(self):
child_win = ChildWindow()
child_win.show()
这是修复问题的好源代码:
def showChildWindow(self):
child_win = ChildWindow(self)
child_win.show()
实例化子窗口时,请确保传递父窗口self。