python按什么键停止运行_python – pyqt5 – 关闭/终止应用程序

我正在努力通过这里找到的pyqt5教程Zetcode, PyQt5

作为我自己的练习,我正在尝试扩展一个示例,以便无论用于关闭应用程序的方法如何,我都会看到相同的对话框消息框:

>单击标题栏中的“X”按钮(按预期工作)

>单击“关闭”按钮(产生属性错误)

>按“退出”键(工作但不确定如何/为什么)

对话框消息框在closeEvent方法中实现,最后提供完整脚本.

我有两个问题:

1.单击“关闭”按钮时,我想调用包含消息框对话框的closeEvent方法,而不是仅退出.

我已经为“关闭”按钮替换了一行示例代码:

btn.clicked.connect(QCoreApplication.instance().quit)

而是尝试调用已实现我想要的对话框的closeEvent方法:

btn.clicked.connect(self.closeEvent)

但是,当我运行脚本并单击“关闭”按钮并在对话框中选择生成的“关闭”选项时,我得到以下内容:

Traceback (most recent call last):

File "5-terminator.py", line 41, in closeEvent

event.accept()

AttributeError: 'bool' object has no attribute 'accept'

Aborted

任何人都可以建议我做错了什么,需要做什么?

2.当以某种方式点击转义键时,会显示消息框对话框并且工作正常.

好的,它的工作原理很棒,但是我想知道在keyPressEvent方法中调用CloseEvent方法中定义的消息框功能的方式和原因.

完整脚本如下:

import sys

from PyQt5.QtWidgets import (

QApplication, QWidget, QToolTip, QPushButton, QMessageBox)

from PyQt5.QtCore import QCoreApplication, Qt

class Window(QWidget):

def __init__(self):

super().__init__()

self.initUI()

def initUI(self):

btn = QPushButton("Close", self)

btn.setToolTip("Close Application")

# btn.clicked.connect(QCoreApplication.instance().quit)

# instead of above button signal, try to call closeEvent method below

btn.clicked.connect(self.closeEvent)

btn.resize(btn.sizeHint())

btn.move(410, 118)

self.setGeometry(30, 450, 500, 150)

self.setWindowTitle("Terminator")

self.show()

def closeEvent(self, event):

"""Generate 'question' dialog on clicking 'X' button in title bar.

Reimplement the closeEvent() event handler to include a 'Question'

dialog with options on how to proceed - Save, Close, Cancel buttons

"""

reply = QMessageBox.question(

self, "Message",

"Are you sure you want to quit? Any unsaved work will be lost.",

QMessageBox.Save | QMessageBox.Close | QMessageBox.Cancel,

QMessageBox.Save)

if reply == QMessageBox.Close:

event.accept()

else:

event.ignore()

def keyPressEvent(self, event):

"""Close application from escape key.

results in QMessageBox dialog from closeEvent, good but how/why?

"""

if event.key() == Qt.Key_Escape:

self.close()

if __name__ == '__main__':

app = QApplication(sys.argv)

w = Window()

sys.exit(app.exec_())

希望有人能抽出时间来启发我.

解决方法:

你的第二个问题回答了第一个问题.

重新实现的keyPressEvent方法调用close(),它将QCloseEvent发送到窗口小部件.随后,将使用该事件作为其参数调用窗口小部件closeEvent.

所以你只需要将按钮连接到widget的close()插槽,一切都会按预期工作:

btn.clicked.connect(self.close)

标签:python,exit,messagebox,pyqt5,terminate

来源: https://codeday.me/bug/20190527/1167120.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值