【发布时间】:2022-12-06 08:51:47
【问题描述】:
我的应用程序允许双击 QTableWidget 单元格来编辑内容,但光标始终位于现有内容的末尾。
not to be selected on edit的内容我已经整理好了。我怎样才能将编辑光标定位在单击鼠标的位置?
【问题讨论】:
-
也许,在同一函数内(取消选择后),通过将全局光标位置映射到小部件,根据
cursorPositionAt()设置光标位置。
标签: pyqt5
我的应用程序允许双击 QTableWidget 单元格来编辑内容,但光标始终位于现有内容的末尾。
not to be selected on edit的内容我已经整理好了。我怎样才能将编辑光标定位在单击鼠标的位置?
【问题讨论】:
cursorPositionAt() 设置光标位置。
标签: pyqt5
这是一种将插入点放置在您在网格单元格中单击的位置的方法。如下所述,您需要将一些东西放在正确的位置。这使用 QTableView 控件而不是 QTableWidget。我不确定会翻译多少。
import PySide2.QtWidgets as qtw
import PySide2.QtGui as qgui
from PySide2.QtCore import Qt
# place the cursor where the mouse was clicked in a cell
# based on https://stackoverflow.com/a/72792962 and a comment
# from @musicamanta at https://stackoverflow.com/q/73346426
class ClickPositionDelegate(QStyledItemDelegate):
# override the createEditor behavior so we can capture the
# first `selectAll` that occurs automatically after the
# QLineEdit control is created.
def createEditor(self, parent, option, index):
editor = super().createEditor(parent, option, index)
# set margins so text in the control aligns with the grid (optional)
editor.setTextMargins(4, 2, 2, 4)
if isinstance(editor, qtw.QLineEdit):
def position_cursor():
# Catch the initial selectAll event via the selectionChanged
# signal; this ensures the position is calculated after the
# control is placed on screen, so cursorPositionAt will work
# correctly.
# Disconnect so setCursorPosition won't call this func again
editor.selectionChanged.disconnect(deselect)
# Get cursor position within the editor's coordinate system
gpos = qgui.QCursor.pos()
lpos = editor.mapFromGlobal(gpos)
editor.setCursorPosition(editor.cursorPositionAt(lpos))
# queue up the positioning function if and only if we got here
# via a simple mouse click (left mouse button is currently down
# with no modifiers)
if (
qgui.QGuiApplication.mouseButtons() == Qt.LeftButton
and qgui.QGuiApplication.keyboardModifiers() == Qt.NoModifier
):
editor.selectionChanged.connect(position_cursor)
return editor
class MainWindow(QMainWindow):
# Constructor
def __init__(self):
# Call the parent class's constructor
super().__init__()
...
# Create the data table
self.table = QTableView(self)
table_view = self.table
# start editing as soon as a cell is selected (no need for Enter
# or double-click)
self.table.setEditTriggers(QAbstractItemView.AllEditTriggers)
# or self.table.setEditTriggers(QTableView.CurrentChanged)
# call our special delegate to position the cursor correctly when
# clicking on a cell
self.table.setItemDelegate(ClickPositionDelegate(self.table))
# Set the central widget of the main window
self.setCentralWidget(self.table)
...
# be sure to run self.table.setModel(some_model) at some point
...
app = QApplication()
window = MainWindow()
window.show()
app.exec_()
【讨论】: