Python Qt 如何从 QMainWindow 打开弹出 QDialog
我正在做一个项目,里面有一个数据库和一个用Python做的界面(我用Qt Designer来设计界面)。我想在我的主窗口(QMainWindow
)上放一个删除按钮,当我按下这个按钮时,它会弹出一个对话框(QDialog
),里面写着:
你确定要删除这个项目吗?
但是我不知道该怎么做。
谢谢你的帮助!
3 个回答
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')
2
假设你的Qt Designer界面有一个主窗口,叫做“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_())
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)
把这个功能绑定到按钮的点击事件上。