【发布时间】:2014-04-08 00:36:55
【问题描述】:
我正在开发一个项目,其中我有一个与 Python 接口链接的数据库(我正在使用 Qt Designer 进行设计)。我想在我的主窗口 (QMainWindow) 中有一个删除按钮,当我按下它时,它会打开一个弹出窗口 (QDialog),上面写着
您确定要删除此项目吗?
但我不知道该怎么做。
感谢您的帮助!
【问题讨论】:
标签: python qt popup qmainwindow qdialog
我正在开发一个项目,其中我有一个与 Python 接口链接的数据库(我正在使用 Qt Designer 进行设计)。我想在我的主窗口 (QMainWindow) 中有一个删除按钮,当我按下它时,它会打开一个弹出窗口 (QDialog),上面写着
您确定要删除此项目吗?
但我不知道该怎么做。
感谢您的帮助!
【问题讨论】:
标签: python qt popup 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 functions 之一来创建对话框。前三个参数设置父级、标题和文本。接下来的两个参数设置显示的按钮组,以及默认按钮(最初突出显示的按钮)。如果您想使用不同的按钮,可以找到可用的按钮here。
要完成示例,您只需要一些代码来启动应用程序并显示窗口:
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
【讨论】:
QMessageBox.question 的第一个参数(在我的示例中为 self)必须是 Qt 小部件。我怀疑您正在尝试传递一个普通的 python 对象,这就是您收到错误的原因。 MyKinectViewer 类是什么?如果没有看到您的代码,就很难进一步诊断问题。
MyKinectViewer 类不是 QGLWidget 的子类。如果是这样,您将不会收到该错误。您可以通过执行print(viewer.__class__.mro()) 来确认这一点,其中viewer 是MyKinectViewer 的一个实例。这将表明它不继承QGLWidget 或QWidget。它可能具有QGLWidget(或其他一些QWidget)的实例作为属性。如果是,则将此小部件(或任何其他小部件,例如您的主窗口)作为第一个参数传递给QMessageBox.question。
我在 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')
【讨论】: