让Enter键的行为类似于QTableWidget中的Tab

时间:2018-07-31 18:46:10

标签: python pyqt pyqt5 qtablewidget

我正在PyQt5和Qt Designer中使用QTableWidget创建数据条目表。我想要的是一种简单的方法,使“ Enter” keyPressEvent像按Tab键一样在表中移动。以下代码捕获Enter键按下事件。如何使其移动光标?

def keyPressEvent(self, ev):        
    if ev.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
        print("Enter key pressed")

1 个答案:

答案 0 :(得分:2)

应该使用keyPressEvent + QShortcut,而不是使用较低级别的focusNextPrevChild(),如下所示:

import sys
from PyQt5 import QtCore, QtWidgets
from functools import partial


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        self.tableWidget = QtWidgets.QTableWidget()
        self.tableWidget.setRowCount(4)
        self.tableWidget.setColumnCount(2)
        for i in range(self.tableWidget.rowCount()):
            for j in range(self.tableWidget.columnCount()):
                it = QtWidgets.QTableWidgetItem("Cell {}{}".format(i, j))
                self.tableWidget.setItem(i, j, it)

        self.layout = QtWidgets.QVBoxLayout(self)
        self.layout.addWidget(self.tableWidget)

        for key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
            QtWidgets.QShortcut(key, self.tableWidget, partial(self.tableWidget.focusNextPrevChild, True))


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    ex = Widget()
    ex.show()
    sys.exit(app.exec_())