QDialog esc怎么退出而不是except
您可以使用QDialog的reject()方法来实现在按下ESC键时退出对话框,而不是使用异常处理。
以下是一个示例代码:
from PyQt5.QtWidgets import QApplication, QDialog, QVBoxLayout, QPushButton
class MyDialog(QDialog):
def __init__(self):
super().__init__()
# 设置对话框的标题和布局
self.setWindowTitle("My Dialog")
layout = QVBoxLayout(self)
# 创建一个按钮
button = QPushButton("Close")
layout.addWidget(button)
# 将按钮的点击信号与对话框的reject()方法关联
button.clicked.connect(self.reject)
def keyPressEvent(self, event):
# 重写keyPressEvent方法,当按下ESC键时调用reject()方法
if event.key() == Qt.Key_Escape:
self.reject()
if __name__ == '__main__':
app = QApplication([])
dialog = MyDialog()
dialog.exec_()
app.quit()
在这个示例中,我们重写了QDialog的keyPressEvent方法,在按下ESC键时调用reject()方法来退出对话框。注意,在调用reject()方法之前,我们还需要检查按下的键是否是ESC键(Qt.Key_Escape)
原文地址: https://www.cveoy.top/t/topic/ipUc 著作权归作者所有。请勿转载和采集!