在Python中显示弹出窗口(PyQt4)

use*_*452 2 python dialog pyqt qt-designer

我需要知道如何在用户单击按钮时弹出对话框.

我对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_())
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我已将第一个按钮连接到名为"popup"的方法,该方法需要填入代码以弹出第二个窗口.我该怎么做呢?请记住,我已经在QtDesigner中设计了第二个对话框,我不需要创建一个新对话框.

感谢您的帮助!

Ava*_*ris 9

正如您所看到的,我已将第一个按钮连接到名为"popup"的方法,该方法需要填入代码以弹出第二个窗口.我该怎么做呢?

几乎和你的主窗口一样(MyForm).

像往常一样,为第二个对话框编写QtDesigner代码的包装类(就像你一样MyForm).我们称之为MyPopupDialog.然后在您的popup方法中,您创建一个实例,然后使用exec_()show()根据您是否需要模态或无模式对话框显示您的实例.(如果您不熟悉Modal/Modeless概念,可以参考文档.)

所以整体事情可能看起来像这样(经过几处修改):

# 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_())
Run Code Online (Sandbox Code Playgroud)