我在显示用户输入一些数据的QWidget窗口时遇到了问题。
我的脚本没有GUI,但我只想显示这个小QWidget窗口。
我用QtDesigner创建了这个窗口,现在我试图像这样显示QWidget窗口:
from PyQt4 import QtGui
from input_data_window import Ui_Form
class childInputData(QtGui.QWidget ):
def __init__(self, parent=None):
super(childInputData, self).__init__()
self.ui = Ui_Form()
self.ui.setupUi(self)
self.setFocus(True)
self.show()然后,在我的主修课上,我就是这样做的:
class myMainClass():
childWindow = childInputData()这给了我一个错误:
QWidget: Must construct a QApplication before a QPaintDevice所以现在我正在做的是,从我的主课上:
class myMainClass():
app = QtGui.QApplication(sys.argv)
childWindow = childInputData() 现在没有错误,但是窗口会被显示两次,并且脚本不会等到数据输入之后,它只显示窗口并且不等待就继续。
这里怎么了?
发布于 2015-11-05 09:42:56
窗口的显示和脚本的继续是完全正常的:您从未告诉脚本等待用户回答。你刚让它展示了一扇窗户。
您想要的是脚本停止,直到用户完成并关闭窗口。
有一种方法可以做到:
from PyQt4 import QtGui,QtCore
import sys
class childInputData(QtGui.QWidget):
def __init__(self, parent=None):
super(childInputData, self).__init__()
self.show()
class mainClass():
def __init__(self):
app=QtGui.QApplication(sys.argv)
win=childInputData()
print("this will print even if the window is not closed")
app.exec_()
print("this will be print after the window is closed")
if __name__ == "__main__":
m=mainClass()exec()方法“进入主事件循环并等待直到exit()被调用”(文档):
脚本将在app.exec_()行上被阻塞,直到窗口关闭。
注意:使用sys.exit(app.exec_())将导致脚本在窗口关闭时结束。
另一种方法是使用QDialog而不是QWidget。然后将self.show()替换为self.exec(),这将阻止脚本
来自文档
int QDialog::exec() 将对话框显示为模态对话框,阻塞直到用户关闭。
最后,相关问题的这个答案建议不要使用exec,而是使用win.setWindowModality(QtCore.Qt.ApplicationModal)设置窗口模式。但是,这在这里不起作用:它阻止其他窗口中的输入,但不阻止脚本。
发布于 2015-11-05 09:15:51
您不需要像这样的myMainClass...do:
import sys
from PyQt4 import QtGui
from input_data_window import Ui_Form
class childInputData(QtGui.QWidget):
def __init__(self, parent=None):
super(childInputData, self).__init__(parent)
self.ui = Ui_Form()
self.ui.setupUi(self)
self.setFocus(True)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
win = childInputData()
win.show()
sys.exit(app.exec_())https://stackoverflow.com/questions/33540421
复制相似问题