English | 简体中文
An editable text item for QGraphicsScene — the kind of "type text anywhere on the canvas" box you expect from an annotation tool. Derived from QAbstractGraphicsShapeItem, it keeps its own QTextDocument and QTextCursor and paints a real blinking caret on the scene.
- Double-click to edit — double-clicking the item enters edit mode; the click position is mapped to the closest text line and character (via
QTextLayout::lineAt+xToCursor()), so multi-line text places the caret where you actually clicked instead of jumping to the end. - Real caret and selection — the caret is drawn by the item itself and toggled by a 500 ms
QTimer, with the caret line computed from the document layout; focus changes start and stop it, and focus-out leaves edit mode cleanly. - Keyboard editing — printable input is inserted into the document, with arrow-key navigation,
Backspace, andCtrl+A(select all, with a translucent blue selection background) andCtrl+C(copy the text to the clipboard).PageUp/PageDownchange the font size. - Input method support —
inputMethodEvent()commits IME strings, andinputMethodQuery()answersImCursorRectangle,ImFont,ImCursorPosition,ImSurroundingTextandImCurrentSelection, so Chinese input keeps its candidate window next to the caret instead of in a screen corner. - Self-sizing geometry — the item's bounding rect follows the document size (
prepareGeometryChange()on every change), so the text never paints outside its own area. - Standard item behaviour kept — movable, selectable, focusable and input-method aware, and the usual dashed selection frame of a graphics item is preserved.
Widget.cpp puts a QGraphicsScene (400×400) inside a QGraphicsView with a single GraphicsTextItem at (100, 100) — double-click it and start typing.
qmake CustomGraphicsTextItem.pro
make # nmake / mingw32-make on WindowsQt 5 with the core gui widgets modules, C++11.
This is an experiment rather than a drop-in QTextEdit: there is no mouse-drag selection, no paste (Ctrl+V), and the caret line is measured character by character with QFontMetrics, so unusual glyph widths or automatic line wrapping are not perfect.
- Related: ShortcutInput — shortcut capture widgets
- Related: qt-designer-custom-widgets — reuseable Sunny widgets