我需要在 QTextEdit 中獲取絕對游標位置(以像素為單位)。
我試試
from PySide6 import QtCore, QtWidgets, QtGui
class MyWidget(QtWidgets.QWidget):
def __init__(self, parent):
super().__init__(parent)
self.text_edit = QtWidgets.QTextEdit(self)
self.text_edit.setGeometry(10, 10, 100, 100)
self.cursor = QtGui.QTextCursor(self.text_edit.document())
self.cursor.insertText('abc yz abc')
self.cursor = QtGui.QTextCursor(self.text_edit.document())
self.cursor.setPosition(4)
self.cursor.movePosition(QtGui.QTextCursor.MoveOperation.Right, QtGui.QTextCursor.MoveMode.KeepAnchor, 2)
self.text_edit.setTextCursor(self.cursor)
print(self.text_edit.cursorRect(self.cursor))
print(self.text_edit.mapToGlobal(self.text_edit.cursorRect(self.cursor).topLeft()))
if __name__ == '__main__':
app = QtWidgets.QApplication([])
dialog = QtWidgets.QDialog()
main = MyWidget(dialog)
dialog.setGeometry(10,10,200,200)
dialog.show()
app.exec()
我等待cursorRect(self.cursor)選擇yz字符的回傳矩形,但它沒有。
uj5u.com熱心網友回復:
您的代碼有兩個基本問題。首先,從檔案(我的重點)...
回傳一個包含游標的矩形(在視口坐標中)。
所以print宣告應該是...
print(self.text_edit.viewport().mapToGlobal(self.text_edit.cursorRect(self.cursor).topLeft()))
其次,您正在從該__init__方法列印游標坐標,因此該小部件不可見,并且不知道真實的幾何形狀。添加一個簡單的paintEvent實作,顯示坐標并安排進一步的更新......
def paintEvent(self, event):
super(MyWidget, self).paintEvent(event)
print(self.text_edit.viewport().mapToGlobal(self.text_edit.cursorRect(self.cursor).topLeft()))
QtCore.QTimer.singleShot(100, self.update)
上面顯示的代碼僅用于演示目的,不應考慮用于“真實”應用程式。但是,它應該輸出正確的游標坐標。
使用簡單 10Hz 的更好示例QTimer是...
from PySide6 import QtCore, QtWidgets, QtGui
class MyWidget(QtWidgets.QWidget):
def __init__(self, parent):
super().__init__(parent)
self.text_edit = QtWidgets.QTextEdit(self)
self.text_edit.setGeometry(10, 10, 100, 100)
self.cursor = QtGui.QTextCursor(self.text_edit.document())
self.cursor.insertText('abc yz abc')
self.cursor = QtGui.QTextCursor(self.text_edit.document())
self.cursor.setPosition(4)
self.cursor.movePosition(QtGui.QTextCursor.MoveOperation.Right, QtGui.QTextCursor.MoveMode.KeepAnchor, 2)
self.text_edit.setTextCursor(self.cursor)
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.show_cursor_position)
self.timer.start(100)
def show_cursor_position(self):
print(self.text_edit.viewport().mapToGlobal(self.text_edit.cursorRect(self.cursor).topLeft()))
if __name__ == '__main__':
app = QtWidgets.QApplication([])
dialog = QtWidgets.QDialog()
main = MyWidget(dialog)
dialog.setGeometry(10,10,200,200)
dialog.show()
app.exec()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/530183.html
標籤:Pythonqtqtexteditpyside6qtextcursor
上一篇:ORA-06576:在Qtc 中不是有效的函式或程序名稱
下一篇:QT事件過濾器優先級問題
