我在显示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()
现在没有错误,但是窗口显示了两次,脚本不等到输入数据后才显示该脚本,而是继续显示窗口而无需等待。
怎么了
最佳答案
显示窗口并继续执行脚本是完全正常的:您从未告诉脚本等待用户回答。您只是告诉它显示一个窗口。
您想要的是脚本停止运行,直到用户完成并关闭窗口。
这是一种实现方法:
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()为止”(doc):该脚本将在
app.exec_()
行上被阻止,直到关闭窗口。注意:使用
sys.exit(app.exec_())
将导致脚本在关闭窗口时结束。另一种方法是使用
QDialog
代替QWidget
。然后,将self.show()
替换为self.exec()
,这将阻止脚本从doc:
int QDialog :: exec()
将对话框显示为模态对话框,直到用户将其关闭为止一直阻塞
最后,相关问题的this answer提倡不要使用
exec
,而应使用win.setWindowModality(QtCore.Qt.ApplicationModal)
设置窗口模态。但是,这在这里不起作用:它会阻止其他窗口中的输入,但不会阻止脚本。关于python - 显示不带MainWindow的Qwidget窗口,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33540421/