gpt4 book ai didi

python - Python 中的击键事件

转载 作者:行者123 更新时间:2023-11-30 23:30:22 25 4
gpt4 key购买 nike

我正在使用 python 2.7 和 Qt4。我需要在按 ctrl+F 键盘后有一个查找对话框。我正在使用这段代码进行测试,但我想这个方法永远不会在我的类中执行。如果您能指导我,我将不胜感激。

我的第一个问题是,当按下按键时,这个方法根本没有被调用!其次,如何组合ctrl和F这两个键。第三,如何调用对话框。我是 python 新手,如果您能帮助我,我将不胜感激......

  def find(self, event):
print("I am here")
key = event.key()
if QtGui.QApplication.keyboardModifiers() == QtCore.Qt.ControlModifier:
#show find dialog
reply=QMessageBox.question(self,'Message',"Find Dialog",QMessageBox.Yes|QMessageBox.No,QMessageBox.No)
if reply==QMessageBox.Yes:
event.accept()
else:
event.ignore()

最佳答案

设置键盘快捷键的常用方法是使用 QAction在菜单中;或者如果没有菜单,则仅显示 QShortcut .

按键序列本身(例如 Ctrl+F)可以使用 QKeySequence 来构造.

下面的脚本显示了设置打开对话框的快捷方式的两种不同方法:

from PyQt4 import QtCore, QtGui

class Window(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
menu = self.menuBar().addMenu('&File')
action = menu.addAction('&Open')
action.setShortcut(QtGui.QKeySequence('Ctrl+F'))
action.triggered.connect(self.handleFind)
shortcut = QtGui.QShortcut(QtGui.QKeySequence('F3'), self)
shortcut.activated.connect(self.handleFind)
label = QtGui.QLabel(self)
label.setText('<center>Press Ctrl+F or F3<center>')
self.setCentralWidget(label)

def handleFind(self):
reply = QtGui.QMessageBox.question(
self, 'Message', 'Find Dialog',
QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
print('Yes')
else:
print('No')

if __name__ == '__main__':

import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.setGeometry(500, 300, 300, 200)
window.show()
sys.exit(app.exec_())

关于python - Python 中的击键事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20622223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com