gpt4 book ai didi

python - PyQt QTableWidget 编辑时的键盘事件

转载 作者:太空宇宙 更新时间:2023-11-04 11:02:50 25 4
gpt4 key购买 nike

我想以类似于 MS Excel 的方式导航 QTableWidget

例如,当用户在编辑一个单元格时按下向右箭头键,编辑将完成并选择右边的下一个单元格。我已经搜索了 Qt 文档,但似乎无法找到方法。

最佳答案

from PyQt4.QtCore import QEvent, Qt
from PyQt4.QtGui import QTableWidget, QWidget, QVBoxLayout, QApplication


class MyTableWidget(QTableWidget):
def __init__(self):
QTableWidget.__init__(self)

self.keys = [Qt.Key_Left,
Qt.Key_Right]

# We need this to allow navigating without editing
self.catch = False

def focusInEvent(self, event):
self.catch = False
return QTableWidget.focusInEvent(self, event)

def focusOutEvent(self, event):
self.catch = True
return QTableWidget.focusOutEvent(self, event)

def event(self, event):
if self.catch and event.type() == QEvent.KeyRelease and event.key() in self.keys:
self._moveCursor(event.key())

return QTableWidget.event(self, event)

def keyPressEvent(self, event):
if not self.catch:
return QTableWidget.keyPressEvent(self, event)

self._moveCursor(event.key())


def _moveCursor(self, key):
row = self.currentRow()
col = self.currentColumn()

if key == Qt.Key_Left and col > 0:
col -= 1

elif key == Qt.Key_Right and col < self.columnCount():
col += 1

elif key == Qt.Key_Up and row > 0:
row -= 1

elif key == Qt.Key_Down and row < self.rowCount():
row += 1

else:
return

self.setCurrentCell(row, col)
self.edit(self.currentIndex())


class Widget(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self)
tableWidget = MyTableWidget()
tableWidget.setRowCount(10)
tableWidget.setColumnCount(10)

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

app = QApplication([])
widget = Widget()
widget.show()
app.exec_()

不确定您是否还需要这个,但这里是。

关于python - PyQt QTableWidget 编辑时的键盘事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3901829/

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