我需要知道当用户点击按钮时如何弹出对话框。
我对Python和PyQt / QtDesigner都比较陌生。我只在他们身上使用了大约一个月,但我认为我掌握得很好。
这就是我所拥有的:一个主要对话框(这是应用程序的主要部分),我在QtDesigner中设计。我使用pyuic4easy将.ui转换为.py。
这就是我想要做的事情:在QtDesigner中设计一个新的对话框,当用户点击第一个(主)对话框上的按钮时,它会以某种方式弹出。
这是我的主对话框的代码:
import sys
from PyQt4.QtCore import *
from loginScreen import *
class MyForm(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_Dialog()
self.ui.setupUi(self)
QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL('clicked()'), self.popup)
...
... Some functions ...
def popup(self):
#Pop-up the new dialog
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp= MyForm()
myapp.show()
sys.exit(app.exec_())
正如您所看到的,我已将第一个按钮连接到名为“popup”的方法,该方法需要填入代码才能弹出第二个窗口。我该怎么做呢?请记住,我已经在QtDesigner中设计了第二个对话框,我不需要创建一个新对话框。
感谢您的帮助!
答案 0 :(得分:9)
正如您所看到的,我已将第一个按钮连接到名为的方法 'popup',需要填写代码才能成为我的第二个 窗口弹出。我该怎么做呢?
与主窗口(MyForm
)完全相同。
像往常一样,为第二个对话框编写QtDesigner代码的包装类(就像使用MyForm
一样)。我们称之为MyPopupDialog
。然后在popup
方法中,创建一个实例,然后使用exec_()
或show()
显示您的实例,具体取决于您是否需要模式或无模式对话框。 (如果您不熟悉Modal / Modeless概念,可以参考documentation.)
所以总的来说可能是这样的(经过一些修改):
# Necessary imports
class MyPopupDialog(QtGui.QDialog):
def __init__(self, parent=None):
# Regular init stuff...
# and other things you might want
class MyForm(QtGui.QDialog):
def __init__(self, parent=None):
# Here, you should call the inherited class' init, which is QDialog
QtGui.QDialog.__init__(self, parent)
# Usual setup stuff
self.ui = Ui_Dialog()
self.ui.setupUi(self)
# Use new style signal/slots
self.ui.pushButton.clicked.connect(self.popup)
# Other things...
def popup(self):
self.dialog = MyPopupDialog()
# For Modal dialogs
self.dialog.exec_()
# Or for modeless dialogs
# self.dialog.show()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp= MyForm()
myapp.show()
sys.exit(app.exec_())