gpt4 book ai didi

python - 如何捕捉 Python PyQt5 QTreeWidget 按 Enter(返回)键?

转载 作者:行者123 更新时间:2023-12-01 08:54:54 27 4
gpt4 key购买 nike

我尝试在按 Enter(返回)键时运行 enterFunc()。但不工作。这是代码,真正的代码是什么?:

class myForm(QMainWindow):

...
def keyPressEvent(self,event):
if(event.key()==Qt.Key_Enter):
enterFunc()
...
myForm.myTreeWidget.keyPressEvent(self,event)
...

最佳答案

第一个 xxxEvent 不是信号,不应被调用,如果您想监听其中一个,您应该使用如下所示的事件过滤器,另一方面,您不应该使用 Qt::Key_Enter 键但 Qt::Key_Return 键:

from PyQt5 import QtCore, QtWidgets, uic


class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
uic.loadUi("ui_mainwindow.ui",self)
self.myTreeWidget.installEventFilter(self)

def eventFilter(self, obj, event):
if obj == self.myTreeWidget:
if event.type() == QtCore.QEvent.KeyPress:
if event.key() == QtCore.Qt.Key_Return:
print("enter pressed")
return super(MainWindow, self).eventFilter(obj, event)


if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

或更轻松地使用QShortcut:

from PyQt5 import QtCore, QtWidgets, uic


class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
uic.loadUi("ui_mainwindow.ui",self)

shorcut = QtWidgets.QShortcut(QtCore.Qt.Key_Return,
self.myTreeWidget,
context=QtCore.Qt.WidgetShortcut,
activated=self.some_function)

def some_function(self):
print("some_function")


if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

关于python - 如何捕捉 Python PyQt5 QTreeWidget 按 Enter(返回)键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52842575/

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