用Python显示弹出窗口(PyQt4)

2024-05-13 00:52:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我对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_())

如您所见,我已将第一个按钮连接到名为“pop up”的方法,该方法需要用代码填充,以使我的第二个窗口弹出。我该怎么做?请记住,我已经在QtDesigner中设计了第二个对话框,不需要创建新的对话框。

谢谢你的帮助!


Tags: 代码用户fromimportselfuidefsys
1条回答
网友
1楼 · 发布于 2024-05-13 00:52:11

So as you can see, I've connected the first button to a method named 'popup', which needs to be filled in with code to make my second window pop up. How do I go about doing this?

几乎和你在主窗口中做的一样(MyForm)。

像往常一样,为第二个对话框的QtDesigner代码编写一个包装类(就像对MyForm所做的那样)。我们称之为MyPopupDialog。然后在popup方法中,创建一个实例,然后使用exec_()show()来显示实例,这取决于您想要的是模态对话框还是非模态对话框。(如果您不熟悉模态/非模态概念,可以参考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_())

相关问题 更多 >