Python Qt如何从QMainWindow打开弹出的QDialog

时间:2014-03-05 18:43:49

标签: python qt popup qmainwindow qdialog

我正在开发一个项目,我有一个与Python接口链接的数据库(我正在使用Qt Designer进行设计)。我想在我的主窗口(QMainWindow)中有一个删除按钮,当我按下它时,会打开一个弹出窗口(QDialog),上面写着

  

您确定要删除此项吗?

但我不知道该怎么做。

谢谢你的帮助!

3 个答案:

答案 0 :(得分:2)

def button_click():
    dialog = QtGui.QMessageBox.information(self, 'Delete?', 'Are you sure you want to delete this item?', buttons = QtGui.QMessageBox.Ok|QtGui.QMessageBox.Cancel)

将此功能绑定到按钮点击事件。

答案 1 :(得分:1)

假设您的Qt Designer ui有一个名为“MainWindow”的主窗口和一个名为“buttonDelete”的按钮。

第一步是设置主窗口类并将按钮的单击信号连接到处理程序:

from PyQt4 import QtCore, QtGui
from mainwindow_ui import Ui_MainWindow

class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.setupUi(self)
        self.buttonDelete.clicked.connect(self.handleButtonDelete)

接下来,您需要向处理信号的MainWindow类添加一个方法并打开对话框:

    def handleButtonDelete(self):
        answer = QtGui.QMessageBox.question(
            self, 'Delete Item', 'Are you sure you want to delete this item?',
            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No |
            QtGui.QMessageBox.Cancel,
            QtGui.QMessageBox.No)
        if answer == QtGui.QMessageBox.Yes:
            # code to delete the item
            print('Yes')
        elif answer == QtGui.QMessageBox.No:
            # code to carry on without deleting
            print('No')
        else:
            # code to abort the whole operation
            print('Cancel')

这使用内置的QMessageBox functions之一来创建对话框。前三个参数设置父级,标题和文本。接下来的两个参数设置显示的按钮组,以及默认按钮(最初突出显示的按钮)。如果您想使用不同的按钮,可以找到可用的按钮here

要完成该示例,您只需要一些代码来启动应用程序并显示窗口:

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

答案 2 :(得分:0)

我在qt5.6

时遇到了同样的错误
TypeError: question(QWidget, str, str, buttons: Union[QMessageBox.StandardButtons, QMessageBox.StandardButton] = QMessageBox.StandardButtons(QMessageBox.Yes|QMessageBox.No), defaultButton: QMessageBox.StandardButton = QMessageBox.NoButton): argument 1 has unexpected type 'Ui_MainWindow'

所以我在以下代码中将self更改为None,然后就可以了。

def handleButtonDelete(self):
    answer = QtGui.QMessageBox.question(
        None, 'Delete Item', 'Are you sure you want to delete this item?',
        QtGui.QMessageBox.Yes | QtGui.QMessageBox.No |
        QtGui.QMessageBox.Cancel,
        QtGui.QMessageBox.No)
    if answer == QtGui.QMessageBox.Yes:
        # code to delete the item
        print('Yes')
    elif answer == QtGui.QMessageBox.No:
        # code to carry on without deleting
        print('No')
    else:
        # code to abort the whole operation
        print('Cancel')
相关问题