-
Notifications
You must be signed in to change notification settings - Fork 0
/
graphicstextitem.cpp
331 lines (286 loc) · 10.6 KB
/
graphicstextitem.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
#include "graphicstextitem.h"
#include <QGuiApplication>
#include <QPainter>
#include <QStyleOptionGraphicsItem>
#include <QTextBlock>
#include <QInputMethod>
#include <Qt>
#include <QClipboard>
static void qt_graphicsItem_highlightSelected(
QGraphicsItem *item, QPainter *painter, const QStyleOptionGraphicsItem *option)
{
const QRectF murect = painter->transform().mapRect(QRectF(0, 0, 1, 1));
if (qFuzzyIsNull(qMax(murect.width(), murect.height())))
return;
const QRectF mbrect = painter->transform().mapRect(item->boundingRect());
if (qMin(mbrect.width(), mbrect.height()) < qreal(1.0))
return;
qreal itemPenWidth;
switch (item->type()) {
case QGraphicsEllipseItem::Type:
itemPenWidth = static_cast<QGraphicsEllipseItem *>(item)->pen().widthF();
break;
case QGraphicsPathItem::Type:
itemPenWidth = static_cast<QGraphicsPathItem *>(item)->pen().widthF();
break;
case QGraphicsPolygonItem::Type:
itemPenWidth = static_cast<QGraphicsPolygonItem *>(item)->pen().widthF();
break;
case QGraphicsRectItem::Type:
itemPenWidth = static_cast<QGraphicsRectItem *>(item)->pen().widthF();
break;
case QGraphicsSimpleTextItem::Type:
itemPenWidth = static_cast<QGraphicsSimpleTextItem *>(item)->pen().widthF();
break;
case QGraphicsLineItem::Type:
itemPenWidth = static_cast<QGraphicsLineItem *>(item)->pen().widthF();
break;
default:
itemPenWidth = 1.0;
}
const qreal pad = itemPenWidth / 2;
const qreal penWidth = 0; // cosmetic pen
const QColor fgcolor = option->palette.windowText().color();
const QColor bgcolor( // ensure good contrast against fgcolor
fgcolor.red() > 127 ? 0 : 255,
fgcolor.green() > 127 ? 0 : 255,
fgcolor.blue() > 127 ? 0 : 255);
painter->setPen(QPen(bgcolor, penWidth, Qt::SolidLine));
painter->setBrush(Qt::NoBrush);
painter->drawRect(item->boundingRect().adjusted(pad, pad, -pad, -pad));
painter->setPen(QPen(option->palette.windowText(), 0, Qt::DashLine));
painter->setBrush(Qt::NoBrush);
painter->drawRect(item->boundingRect().adjusted(pad, pad, -pad, -pad));
}
GraphicsTextItem::GraphicsTextItem(const QString &text, QAbstractGraphicsShapeItem *parent)
: QAbstractGraphicsShapeItem(parent)
, m_text(text)
, m_textDocument(nullptr)
, m_textCursor(nullptr)
, m_isEditing(false)
{
// setFocusProxy(Qt::StrongFocus);
// setAttribute(Qt::WA_InputMethodEnabled, true);
m_isDisplayTextCursor = false;
m_textDocument = new QTextDocument(this);
m_textDocument->setDefaultFont(m_font);
m_textCursor = new QTextCursor(m_textDocument);
m_textCursor->insertText(m_text);
m_boundingRect.setSize(m_textDocument->size());
m_timer.setInterval(500);
setFlags(ItemIsMovable | ItemIsSelectable | ItemIsFocusable | ItemAcceptsInputMethod);
connect(m_textDocument, &QTextDocument::contentsChanged, this, &GraphicsTextItem::test);
connect(m_textDocument, &QTextDocument::contentsChanged, this, &GraphicsTextItem::calcCursorPos);
connect(&m_timer, &QTimer::timeout, this, &GraphicsTextItem::cursorFlag);
}
QRectF GraphicsTextItem::boundingRect() const
{
return m_boundingRect;
}
void GraphicsTextItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(widget)
painter->save();
// QPen p(Qt::red);
// painter->setPen(p);
// painter->setFont(m_font);
m_textDocument->drawContents(painter, m_boundingRect);
painter->restore();
if((option->state & QStyle::State_HasFocus) && m_isDisplayTextCursor)
painter->drawLine(m_textCursorPos1, m_textCursorPos2);
if(option->state & (QStyle::State_Selected | QStyle::State_HasFocus))
qt_graphicsItem_highlightSelected(this, painter, option);
}
void GraphicsTextItem::focusOutEvent(QFocusEvent *event)
{
Q_UNUSED(event);
m_isEditing = false;
m_isDisplayTextCursor = false;
m_timer.stop();
setCursor(Qt::ArrowCursor);
}
void GraphicsTextItem::keyPressEvent(QKeyEvent *event)
{
int key = event->key();
bool modified = false;
int add = 1;
if (event->modifiers() & Qt::ControlModifier) {
if (key == Qt::Key_A) {
// Ctrl + A: 全选文本
m_textCursor->select(QTextCursor::Document);
QTextCharFormat fmt;
fmt.setBackground(QBrush(QColor(0, 129, 255, 0.5 * 255))); // 设置选中状态的背景色
m_textCursor->setCharFormat(fmt);
modified = true;
} else if (key == Qt::Key_C) {
// Ctrl + C: 复制选中的文本到剪切板
QClipboard *clipboard = QGuiApplication::clipboard();
clipboard->setText(m_textDocument->toPlainText());
}
} else {
switch (key) {
case Qt::Key_PageUp: {
m_font.setPointSize(m_font.pointSize() + add);
test();
}
break;
case Qt::Key_PageDown: {
m_font.setPointSize(m_font.pointSize() - add);
test();
}
break;
case Qt::Key_Left:
if (m_textCursor->movePosition(QTextCursor::Left)) {
modified = true;
}
break;
case Qt::Key_Right:
if (m_textCursor->movePosition(QTextCursor::Right)) {
modified = true;
}
break;
case Qt::Key_Up:
if (m_textCursor->movePosition(QTextCursor::Up)) {
modified = true;
}
break;
case Qt::Key_Down:
if (m_textCursor->movePosition(QTextCursor::Down)) {
modified = true;
}
break;
case Qt::Key_Enter:
modified = true;
break;
case Qt::Key_Backspace:
m_textCursor->deletePreviousChar();
modified = true;
break;
default:
m_textCursor->insertText(event->text());
modified = true;
break;
}
if(modified){
m_text = m_textDocument->toPlainText();
calcCursorPos();
update();
}
}
}
// fix: 鼠标点击时,在多行文字情况下,显示的光标位置是符合预期的
void GraphicsTextItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
m_isEditing = true; // 进入编辑状态
m_isDisplayTextCursor = true;
// 将点击位置映射到文档中的相对位置
QPointF clickPos = event->pos();
// 遍历文档中的每一个文本块(段落)
QTextBlock block = m_textDocument->firstBlock();
QTextCursor closestCursor = *m_textCursor; // 用来存储最近的光标位置
double minDistance = std::numeric_limits<double>::max();
while (block.isValid()) {
QTextLayout *layout = block.layout();
if (layout) {
// 遍历当前文本块中的每一行
for (int i = 0; i < layout->lineCount(); ++i) {
QTextLine line = layout->lineAt(i);
if (line.isValid()) {
QRectF lineRect = line.naturalTextRect();
lineRect.moveTop(lineRect.top() + block.layout()->position().y()); // 计算行的绝对位置
// 判断鼠标点击位置是否在当前行的范围内
if (lineRect.contains(clickPos)) {
int pos = line.xToCursor(clickPos.x(), QTextLine::CursorOnCharacter);
QTextCursor tempCursor = QTextCursor(block);
tempCursor.setPosition(pos + block.position());
// 计算当前位置和点击位置的横向距离
qreal cursorXPos = line.cursorToX(pos);
double distance = std::abs(cursorXPos - clickPos.x());
// 更新最近的光标位置
if (distance < minDistance) {
minDistance = distance;
closestCursor = tempCursor;
}
}
}
}
}
block = block.next(); // 继续遍历下一个文本块
}
// 将光标设置到计算出的最接近位置
m_textCursor->setPosition(closestCursor.position());
calcCursorPos(); // 计算光标位置
cursorFlag(); // 显示光标
m_timer.start(); // 光标闪烁计时
setCursor(Qt::IBeamCursor);
update(); // 更新视图以反映更改
}
void GraphicsTextItem::inputMethodEvent(QInputMethodEvent *event)
{
if (event->commitString().isEmpty()) return;
// 插入输入法事件的文本
m_textCursor->insertText(event->commitString());
m_text = m_textDocument->toPlainText();
calcCursorPos();
update();
}
QVariant GraphicsTextItem::inputMethodQuery(Qt::InputMethodQuery query) const
{
switch (query) {
case Qt::ImCursorRectangle: {
QRectF cursorRect(m_textCursorPos1, QSizeF(1, m_textCursorPos2.y() - m_textCursorPos1.y()));
return cursorRect;
}
case Qt::ImFont:
return m_font;
case Qt::ImCursorPosition:
return m_textCursor->position();
case Qt::ImSurroundingText:
return m_text;
case Qt::ImCurrentSelection:
return m_textCursor->selectedText();
default:
return QVariant();
}
}
QVariant GraphicsTextItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{
return QGraphicsItem::itemChange(change, value);
}
void GraphicsTextItem::test()
{
qDebug() << "m_font:" << m_font;
m_textDocument->setDefaultFont(m_font);
prepareGeometryChange();
m_boundingRect.setSize(m_textDocument->size());
calcCursorPos();
}
void GraphicsTextItem::calcCursorPos()
{
int pos = m_textCursor->position();
QString text = m_textDocument->toPlainText();
QFontMetrics metrics(m_font);
int pixelPosX = m_textDocument->documentMargin();
int flag = 0; //换行符
for (int i = 0; i < pos; ++i) {
if( text.at(i) == '\n') {
pixelPosX = m_textDocument->documentMargin();
flag++;
continue;
}
QChar ch = text.at(i);
pixelPosX += metrics.width(ch);
}
int pixelPosY = m_textDocument->documentMargin() + /*metrics.leading() +*/ flag * (metrics.leading() + metrics.height());
//p1
QPointF p1(pixelPosX, pixelPosY);
m_textCursorPos1 = p1;
//p2
pixelPosY = p1.y() + metrics.ascent() + metrics.descent();
m_textCursorPos2 = QPointF(pixelPosX, pixelPosY);
}
void GraphicsTextItem::cursorFlag()
{
m_isDisplayTextCursor = !m_isDisplayTextCursor;
update();
}