2015-11-05 89 views
1

我有问题显示用户输入一些数据的QWidget窗口。显示没有MainWindow的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() 

现在没有错误,但是窗口显示两次,脚本不会等待输入数据,它只是显示窗口并继续等待。

这里有什么问题?

+0

关于显示两次的窗口,我看不出为什么在您发布的代码中。你确定你不在代码中的其他地方调用show()吗? – Mel

+0

是的,我是:S .....我的错 – codeKiller

回答

1

这是完全正常时显示的窗口和脚本接着说:你从来没有告诉脚本等待用户来回答。你刚刚告诉它显示一个窗口。

您想要的是在用户完成并关闭窗口之前停止的脚本。

这里有一个办法做到这一点:

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()方法“进入主事件循环并等待退出()被调用”(doc):
脚本将被阻止上线app.exec_()直到窗口关闭。

注意:使用sys.exit(app.exec_())会导致脚本在窗口关闭时结束。


的另一种方法是使用QDialog,而不是QWidget。然后,您可以通过self.exec()更换self.show(),这将阻止脚本

doc

int QDialog::exec()

Shows the dialog as a modal dialog, blocking until the user closes it


最后,一个相关的问题的this answer提倡不使用exec,但设置与窗口模式win.setWindowModality(QtCore.Qt.ApplicationModal)。然而这在这里不起作用:它在其他窗口中阻止输入,但不阻止脚本。

+0

谢谢,这正是我一直在寻找的行为 – codeKiller

0

你不需要的myMainClass ......做这样的事情:

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_()) 
+0

谢谢jramm,我知道我可以做到这一点,我一直在做我的GUI,但在我的问题上,我的意思是我想从我的课堂中显示窗口小部件,这是不可能的? – codeKiller

+0

我不明白为什么它不会工作,如果你将'win.show()'移动到类的'__init__'方法...但它有什么不同? – jramm

+0

再次感谢,没有区别,只是想了解,如果这是可能的 – codeKiller