class Ui_MainWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
app.atexit.connect(self.exitApp)
def exitApp(self):
atexit.register(self.exitApp(app))
ret = QtGui.QMessageBox.question(None, 'Close request', 'Are you sure you want to quit?',
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.Yes)
if ret == QtGui.QMessageBox.Yes:
sys.exit(app.exec())
elif ret == QtGui.QMessageBox.No:
pass
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(1280, 760)
MainWindow.setMaximumSize(QtCore.QSize(16777215, 16777215))
def main():
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.showMaximized()
Ui_MainWindow.loadData(ui)
sys.exit(app.exec_())
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
main()
我想显示一个消息框,显示"您确定要退出吗?"当用户点击Windows关闭按钮(顶部的X按钮)时。
当用户点击按钮时如何获得信号?
解决方案可能与Detect when the "x" or close button is pressed类似,但我使用的是PyQt4。
答案 0 :(得分:1)
如果您不希望窗口关闭,则必须覆盖closeEvent方法并忽略该事件。我已经修改了你的代码,因为我在复制它时遇到了问题。
class MainWindow(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
def closeEvent(self, event):
ret = QtGui.QMessageBox.question(None, 'Close request', 'Are you sure you want to quit?',
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
QtGui.QMessageBox.Yes)
if ret == QtGui.QMessageBox.Yes:
QtGui.QMainWindow.closeEvent(self, event)
else:
event.ignore()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
ui = MainWindow()
ui.show()
sys.exit(app.exec_())