[英]PY Qt Open a QDialog from a QMainWindow
I am working with python code generated using QT Designer. 我正在使用使用QT Designer生成的python代码。 I want to open a new dialogue from a button on my MainWindow.
我想通过MainWindow上的一个按钮打开一个新对话框。 When I use the following code, the dialogue window disappears as soon as it is created.
当我使用以下代码时,对话窗口一创建便消失。 I assume this is because the QDialog object is destroyed when the method hits the return statement.
我认为这是因为当方法命中return语句时,QDialog对象被破坏了。 What is the right way to call this dialogue?
进行此对话的正确方法是什么?
def OpenDialogue(self):
DialogueWindow = QtGui.QDialog()
my_dialogue = MyDialogue.Ui_Dialog()
my_dialogue.setupUi(DialogueWindow)
DialogueWindow.show()
return
For example, should I instantiate DialogueWindow in the same place that I define MainWindow and pass it through to this method? 例如,是否应该在定义MainWindow的同一位置实例化DialogueWindow并将其传递给此方法?
The MainWindow constructor is as follows: MainWindow构造函数如下:
class Ui_MainWindow(QtGui.QMainWindow, object):
def setupUi(self, MainWindow):
[code]
It is instantiated as follows: 实例化如下:
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = GUI.Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
app.exec_()
I will call Ui_MainWindow and Ui_Dialog to the classes generated by Qt Designer through the MainWindow and Dialog template, respectively. 我将分别通过MainWindow和Dialog模板分别调用Ui_MainWindow和Ui_Dialog到Qt Designer生成的类中。 Then it is best to create classes that MainWindow and Dialog implement the interfaces.
然后,最好创建MainWindow和Dialog实现接口的类。 I will call pushButton to the button that you refer, then you must pass the parent to the dialog object.
我将把pushButton调用到您所引用的按钮,然后必须将父级传递给对话框对象。
class Ui_Dialog(object):
def setupUi(self, Dialog):
[...]
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
[...]
class Dialog(QtGui.QDialog, Ui_Dialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
self.setupUi(self)
class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.openDialog)
def openDialog(self):
d = Dialog(self)
d.show()
Another solution is to use exec_()
by opening the window in non-modal mode 另一种解决方案是通过在非模式模式下打开窗口来使用
exec_()
def openDialog(self):
d = Dialog(self)
d.exec_()
Note: It is not recommended to modify the classes generated by Qt Designer. 注意:不建议修改Qt Designer生成的类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.