簡體   English   中英

Python Qt如何從QMainWindow打開彈出的QDialog

[英]Python Qt How to open a pop up QDialog from a QMainWindow

我正在一個項目中,我有一個與Python接口鏈接的數據庫(我正在使用Qt Designer進行設計)。 我想從主窗口( QMainWindow )中有一個刪除按鈕,當我按下它時,它將打開一個彈出窗口( QDialog ),其中顯示

你確定要刪除這個項目嗎?

但是我不知道該怎么做。

感謝您的幫助!

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)

將此功能綁定到按鈕單擊事件。

假設您的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函數之一來創建對話框。 前三個參數設置父項,標題和文本。 接下來的兩個參數設置顯示的按鈕組以及默認按鈕(最初突出顯示的按鈕)。 如果要使用其他按鈕,可以在此處找到可用的按鈕。

為了完成示例,您只需要一些代碼即可啟動應用程序並顯示窗口:

if __name__ == '__main__':

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

我對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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM