-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnoteeditwidget.cpp
More file actions
1768 lines (1476 loc) · 62.1 KB
/
noteeditwidget.cpp
File metadata and controls
1768 lines (1476 loc) · 62.1 KB
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "noteeditwidget.h"
#include "ui_noteeditwidget.h"
#include <QDateTime>
#include <QMessageBox>
#include <QTextCharFormat>
#include <QFileDialog>
#include <QImageReader>
#include <QDebug>
#include <QScreen>
#include <QClipboard>
#include <QMimeData>
#include <QMenu>
#include <QAction>
#include <QBuffer>
#include <QKeyEvent>
#include <QResizeEvent>
#include <QTextDocument>
#include <QTextImageFormat>
#include <QTextBlock>
#include <QTextFragment>
#include <QTimer>
#include <QTextCursor>
#include <QDir>
#include <QUuid>
#include <QFile>
#include <QFileInfo>
#include <QApplication>
#include <QGuiApplication>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QSpacerItem>
#include <QLabel>
#include <QRegularExpression>
NoteEditWidget::NoteEditWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::NoteEditWidget),
m_database(new NoteDatabase(this)),
m_autoSaveTimer(new QTimer(this)),
m_isNewNote(false),
m_hasChanges(false),
m_isLoadingNote(false),
m_isStayOnTop(false),
m_imageEventFilter(new ImageEventFilter(this))
{
ui->setupUi(this);
// 设置窗口属性,允许调整大小,但禁用最大化按钮
setWindowFlags(Qt::Window | Qt::CustomizeWindowHint | Qt::WindowTitleHint |
Qt::WindowSystemMenuHint | Qt::WindowCloseButtonHint |
Qt::WindowMinimizeButtonHint);
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
setMinimumSize(300, 400);
// 设置自动保存定时器
m_autoSaveTimer->setInterval(3000); // 3秒钟自动保存
// 确保图片目录存在
ensureImageDirectoryExists();
setupUI();
setupConnections();
setupImageInteractions();
// 打开数据库
if (!m_database->open()) {
QMessageBox::warning(this, "错误", "无法打开数据库");
}
}
NoteEditWidget::~NoteEditWidget()
{
// 如果有未保存的更改,保存它们
if (m_hasChanges) {
saveChanges();
}
// 清理临时图片
cleanupUnusedImages();
// 清理缓存的原始图片
m_originalImages.clear();
delete ui;
}
void NoteEditWidget::setupUI()
{
// 设置窗口和内容区域的背景色为白色
setStyleSheet("QWidget { background-color: white; }");
// 按钮样式 - 设置白色背景
QString buttonStyle =
"QPushButton { border: 1px solid #CCCCCC; border-radius: 3px; padding: 3px; background-color: white; }"
"QPushButton:hover { background-color: #F0F0F0; }"
"QPushButton:pressed { background-color: #E0E0E0; }"
"QPushButton:checked { background-color: #D0D0D0; }";
// 标题栏样式 - 设置白色背景
ui->titleLineEdit->setStyleSheet(
"QLineEdit { border: none; border-bottom: 1px solid #CCCCCC; "
"padding: 8px; font-size: 14pt; font-weight: bold; background-color: white; }");
// 内容编辑区样式 - 设置白色背景和美化滚动条
ui->contentTextEdit->setStyleSheet(
"QTextEdit { "
" border: none; "
" padding: 5px; "
" background-color: white; "
"} "
"QScrollBar:vertical { "
" background: transparent; "
" width: 8px; "
" margin: 0px; "
" border-radius: 4px; "
"} "
"QScrollBar::handle:vertical { "
" background: #CCCCCC; "
" min-height: 30px; "
" border-radius: 4px; "
"} "
"QScrollBar::handle:vertical:hover { "
" background: #AAAAAA; "
"} "
"QScrollBar::handle:vertical:pressed { "
" background: #888888; "
"} "
"QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical { "
" border: none; "
" background: none; "
" height: 0px; "
"} "
"QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { "
" background: none; "
"} "
"QScrollBar:horizontal { "
" background: transparent; "
" height: 8px; "
" margin: 0px; "
" border-radius: 4px; "
"} "
"QScrollBar::handle:horizontal { "
" background: #CCCCCC; "
" min-width: 30px; "
" border-radius: 4px; "
"} "
"QScrollBar::handle:horizontal:hover { "
" background: #AAAAAA; "
"} "
"QScrollBar::handle:horizontal:pressed { "
" background: #888888; "
"} "
"QScrollBar::add-line:horizontal, QScrollBar::sub-line:horizontal { "
" border: none; "
" background: none; "
" width: 0px; "
"} "
"QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal { "
" background: none; "
"} ");
// 设置底部按钮样式
ui->boldButton->setStyleSheet(buttonStyle);
ui->italicButton->setStyleSheet(buttonStyle);
ui->underlineButton->setStyleSheet(buttonStyle);
ui->imageButton->setStyleSheet(buttonStyle);
ui->deleteButton->setStyleSheet(buttonStyle);
// 设置删除按钮的文本为图标
ui->deleteButton->setText("✕");
// 创建窗口置顶按钮
m_stayOnTopButton = new QPushButton(this);
m_stayOnTopButton->setToolTip("窗口置顶");
m_stayOnTopButton->setStyleSheet(buttonStyle);
m_stayOnTopButton->setCheckable(true);
m_stayOnTopButton->setMaximumSize(30, 30);
m_stayOnTopButton->setText("📌"); // 使用图钉emoji作为图标
// 添加置顶按钮到布局
if (ui->horizontalLayout_2->indexOf(m_stayOnTopButton) == -1) {
ui->horizontalLayout_2->insertWidget(0, m_stayOnTopButton);
}
// 设置字体样式按钮的文本
ui->boldButton->setFont(QFont("Arial", 9, QFont::Bold));
ui->italicButton->setFont(QFont("Arial", 9, QFont::StyleItalic));
QFont underlineFont("Arial", 9);
underlineFont.setUnderline(true);
ui->underlineButton->setFont(underlineFont);
// 确保删除按钮在底部工具栏
if (ui->horizontalLayout_2->indexOf(ui->deleteButton) == -1) {
ui->horizontalLayout_2->addWidget(ui->deleteButton);
}
// 使用调色板明确设置背景色
QPalette pal = palette();
pal.setColor(QPalette::Window, Qt::white);
pal.setColor(QPalette::Base, Qt::white);
setPalette(pal);
ui->titleLineEdit->setPalette(pal);
ui->contentTextEdit->setPalette(pal);
// 设置窗口大小
resize(450, 550);
// 居中显示窗口
if (QGuiApplication::screens().size() > 0) {
QScreen *screen = QGuiApplication::screens().at(0);
move(screen->geometry().center() - rect().center());
}
// 更新置顶按钮状态
updateStayOnTopButton();
// 获取字数统计标签指针
m_wordCountLabel = findChild<QLabel*>("wordCountLabel");
if (m_wordCountLabel) {
m_wordCountLabel->setText("字数:0");
}
}
void NoteEditWidget::setupConnections()
{
connect(ui->contentTextEdit, &QTextEdit::textChanged, this, &NoteEditWidget::onContentChanged);
connect(ui->contentTextEdit, &QTextEdit::textChanged, this, &NoteEditWidget::updateWordCount);
connect(ui->titleLineEdit, &QLineEdit::textChanged, this, &NoteEditWidget::onTitleChanged);
connect(ui->boldButton, &QPushButton::clicked, this, &NoteEditWidget::onBoldButtonClicked);
connect(ui->italicButton, &QPushButton::clicked, this, &NoteEditWidget::onItalicButtonClicked);
connect(ui->underlineButton, &QPushButton::clicked, this, &NoteEditWidget::onUnderlineButtonClicked);
connect(ui->deleteButton, &QPushButton::clicked, this, &NoteEditWidget::onDeleteButtonClicked);
connect(m_autoSaveTimer, &QTimer::timeout, this, &NoteEditWidget::onAutoSaveTimeout);
connect(m_stayOnTopButton, &QPushButton::clicked, this, &NoteEditWidget::onStayOnTopClicked);
// 安装事件过滤器监听粘贴事件
ui->contentTextEdit->installEventFilter(this);
// 连接右键菜单
createContextMenu();
connect(ui->imageButton, &QPushButton::clicked, [this]() {
QString fileName = QFileDialog::getOpenFileName(this, "插入图片",
QString(),
"图片文件 (*.png *.jpg *.jpeg *.bmp *.gif)");
if (!fileName.isEmpty()) {
QImage image(fileName);
if (!image.isNull()) {
// 保存原始图片
QImage originalImage = image;
// 获取设备像素比,处理Windows屏幕缩放问题
qreal devicePixelRatio = qApp->devicePixelRatio();
if (devicePixelRatio > 1.0) {
// 确保原始图像保持正确的设备像素比
originalImage.setDevicePixelRatio(1.0); // 重置为原始像素
}
// 调整图片大小
image = resizeImageToFitWidth(image);
// 保存图片到文件
QString filePath = saveImageToFile(originalImage, "file");
// 生成资源名称
static int fileImageCounter = 0;
QString imageName = QString("file_image_%1").arg(++fileImageCounter);
// 将图片添加到文档资源
ui->contentTextEdit->document()->addResource(
QTextDocument::ImageResource,
QUrl(filePath),
QVariant(image));
// 计算显示尺寸,考虑设备像素比
int displayWidth = image.width() / image.devicePixelRatio();
int displayHeight = image.height() / image.devicePixelRatio();
// 创建图片格式
QTextImageFormat imageFormat;
imageFormat.setName(filePath);
imageFormat.setWidth(displayWidth);
imageFormat.setHeight(displayHeight);
// 插入图片到光标位置
ui->contentTextEdit->textCursor().insertImage(imageFormat);
// 记录临时图片映射
m_tempImages[imageName] = filePath;
// 标记文档已修改
m_hasChanges = true;
m_autoSaveTimer->start();
}
}
});
// 当文本编辑器光标位置改变时,更新格式按钮状态
connect(ui->contentTextEdit, &QTextEdit::cursorPositionChanged, this, &NoteEditWidget::updateFormattingButtons);
}
void NoteEditWidget::setNote(const Note ¬e)
{
m_isLoadingNote = true;
// 如果当前有未保存的更改,保存它们
if (m_hasChanges) {
saveChanges();
}
m_currentNote = note;
m_isNewNote = false;
// 设置标题和内容
QString title = note.title();
ui->titleLineEdit->setText(title);
ui->contentTextEdit->setHtml(note.content());
// 预先显示窗口,确保viewport大小已确定
show();
// 处理内容中的图片引用
QTimer::singleShot(10, this, [this]() {
processContentAfterLoading();
});
// 更新窗口标题
setWindowTitle(title.isEmpty() ? "便签" : title);
m_hasChanges = false;
m_isLoadingNote = false;
// 停止自动保存计时器
m_autoSaveTimer->stop();
// 避免窗口重叠,给窗口位置添加一个小偏移
static int offsetCounter = 0;
if (QGuiApplication::screens().size() > 0) {
QScreen *screen = QGuiApplication::screens().at(0);
QRect screenGeometry = screen->geometry();
// 计算基础位置(屏幕中心)
QPoint basePos = screenGeometry.center() - rect().center();
// 添加偏移(循环使用,避免窗口跑出屏幕)
const int maxOffset = 200;
int xOffset = (offsetCounter % 10) * 30;
int yOffset = ((offsetCounter / 10) % 10) * 30;
// 确保窗口在屏幕内
QPoint newPos = basePos + QPoint(xOffset, yOffset);
if (newPos.x() + width() > screenGeometry.right() - 20) {
newPos.setX(screenGeometry.right() - width() - 20);
}
if (newPos.y() + height() > screenGeometry.bottom() - 20) {
newPos.setY(screenGeometry.bottom() - height() - 20);
}
move(newPos);
// 更新偏移计数器
offsetCounter = (offsetCounter + 1) % 100;
}
// 如果窗口是置顶状态,确保置顶标志生效
if (m_isStayOnTop) {
// 保存当前位置
QRect geometry = this->geometry();
// 应用窗口标志,确保包含置顶标志
Qt::WindowFlags flags = windowFlags();
flags |= Qt::WindowStaysOnTopHint;
setWindowFlags(flags);
// 恢复位置
setGeometry(geometry);
show();
}
activateWindow(); // 确保窗口获得焦点
// 更新字数统计
updateWordCount();
}
void NoteEditWidget::createNewNote()
{
m_isLoadingNote = true;
// 如果当前有未保存的更改,保存它们
if (m_hasChanges) {
saveChanges();
}
// 创建新的笔记对象
m_currentNote = Note();
m_isNewNote = true;
// 清空表单
ui->titleLineEdit->clear();
ui->contentTextEdit->clear();
// 更新窗口标题
setWindowTitle("新建便签");
m_hasChanges = false;
m_isLoadingNote = false;
// 设置焦点到标题输入框
ui->titleLineEdit->setFocus();
// 显示窗口
show();
// 如果窗口是置顶状态,确保置顶标志生效
if (m_isStayOnTop) {
// 保存当前位置
QRect geometry = this->geometry();
// 应用窗口标志,确保包含置顶标志
Qt::WindowFlags flags = windowFlags();
flags |= Qt::WindowStaysOnTopHint;
setWindowFlags(flags);
// 恢复位置
setGeometry(geometry);
show();
}
activateWindow(); // 确保窗口获得焦点
// 更新字数统计
updateWordCount();
}
Note NoteEditWidget::getCurrentNote() const
{
return m_currentNote;
}
bool NoteEditWidget::hasChanges() const
{
return m_hasChanges;
}
void NoteEditWidget::saveChanges()
{
if (!m_hasChanges) {
return;
}
// 处理内容中的图片引用,确保持久化
processContentForSaving();
// 获取标题和内容
QString title = ui->titleLineEdit->text().trimmed();
QString content = ui->contentTextEdit->toHtml();
// 更新笔记内容
m_currentNote.setTitle(title);
m_currentNote.setContent(content);
m_currentNote.setUpdateTime(QDateTime::currentDateTime());
// 更新窗口标题
setWindowTitle(title.isEmpty() ? "便签" : title);
// 保存到数据库
if (m_database->saveNote(m_currentNote)) {
m_hasChanges = false;
m_isNewNote = false;
// 获取便签ID
int noteId = m_currentNote.id();
// 如果有临时图片,将其移动到便签特定目录
if (!m_tempImages.isEmpty() && noteId > 0) {
QString noteDirPath = getImageDirectory(noteId);
QDir dir;
if (!dir.exists(noteDirPath)) {
dir.mkpath(noteDirPath);
}
// 移动临时图片到便签目录
for (auto it = m_tempImages.begin(); it != m_tempImages.end(); ++it) {
QString sourcePath = it.value();
QString fileName = QFileInfo(sourcePath).fileName();
QString targetPath = QString("%1/%2").arg(noteDirPath, fileName);
// 如果源和目标不同,且目标不存在,则移动文件
if (sourcePath != targetPath && !QFile::exists(targetPath)) {
QFile::copy(sourcePath, targetPath);
}
}
// 清空临时图片映射
m_tempImages.clear();
}
// 发送保存成功信号
emit noteSaved(m_currentNote);
}
}
void NoteEditWidget::closeEvent(QCloseEvent *event)
{
// 如果有未保存的更改,保存它们
if (m_hasChanges) {
saveChanges();
}
// 发送关闭信号
emit closed();
// 接受关闭事件
event->accept();
// 非模态对话框需要在关闭时自行删除,以防内存泄漏
// 不过只有当窗口彻底独立(没有父窗口)且主窗口已经关闭时才这样做
if (!parent() && !property("keepAlive").toBool()) {
deleteLater();
}
}
void NoteEditWidget::onContentChanged()
{
if (m_isLoadingNote) {
return;
}
m_hasChanges = true;
m_autoSaveTimer->start(); // 重新启动自动保存计时器
}
void NoteEditWidget::onTitleChanged()
{
if (m_isLoadingNote) {
return;
}
m_hasChanges = true;
// 更新窗口标题
QString title = ui->titleLineEdit->text().trimmed();
setWindowTitle(title.isEmpty() ? "便签" : title);
m_autoSaveTimer->start(); // 重新启动自动保存计时器
}
void NoteEditWidget::onBoldButtonClicked()
{
QTextCharFormat format;
format.setFontWeight(ui->boldButton->isChecked() ? QFont::Bold : QFont::Normal);
ui->contentTextEdit->mergeCurrentCharFormat(format);
ui->contentTextEdit->setFocus();
}
void NoteEditWidget::onItalicButtonClicked()
{
QTextCharFormat format;
format.setFontItalic(ui->italicButton->isChecked());
ui->contentTextEdit->mergeCurrentCharFormat(format);
ui->contentTextEdit->setFocus();
}
void NoteEditWidget::onUnderlineButtonClicked()
{
QTextCharFormat format;
format.setFontUnderline(ui->underlineButton->isChecked());
ui->contentTextEdit->mergeCurrentCharFormat(format);
ui->contentTextEdit->setFocus();
}
void NoteEditWidget::onDeleteButtonClicked()
{
// 如果是新笔记且未保存,直接清空
if (m_isNewNote && m_currentNote.id() == -1) {
ui->titleLineEdit->clear();
ui->contentTextEdit->clear();
return;
}
// 确认是否删除
QMessageBox::StandardButton reply = QMessageBox::question(
this, "确认删除", "确定要删除这条笔记吗?",
QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::Yes) {
int noteId = m_currentNote.id();
// 从数据库中删除
if (m_database->deleteNote(noteId)) {
// 删除便签对应的图片文件夹
QString imageDirPath = getImageDirectory(noteId);
if (!imageDirPath.isEmpty()) {
QDir imageDir(imageDirPath);
if (imageDir.exists()) {
// 递归删除目录及其内容
imageDir.removeRecursively();
qDebug() << "已删除便签图片目录:" << imageDirPath;
}
}
// 发送删除信号
emit noteDeleted(noteId);
// 清空编辑器
ui->titleLineEdit->clear();
ui->contentTextEdit->clear();
m_currentNote = Note();
m_hasChanges = false;
m_isNewNote = true;
// 关闭窗口
close();
}
}
}
void NoteEditWidget::onAutoSaveTimeout()
{
if (m_hasChanges) {
saveChanges();
}
}
void NoteEditWidget::updateFormattingButtons()
{
QTextCharFormat format = ui->contentTextEdit->currentCharFormat();
ui->boldButton->setChecked(format.fontWeight() == QFont::Bold);
ui->italicButton->setChecked(format.fontItalic());
ui->underlineButton->setChecked(format.fontUnderline());
}
void NoteEditWidget::updateTitleLabel()
{
QString title = ui->titleLineEdit->text().trimmed();
if (title.isEmpty()) {
setWindowTitle("新建便签");
} else {
// 如果标题太长,截断并加上省略号
if (title.length() > 40) {
setWindowTitle(title.left(40) + "...");
} else {
setWindowTitle(title);
}
}
}
int NoteEditWidget::getNoteId() const
{
return m_currentNote.id();
}
// 切换窗口置顶状态
void NoteEditWidget::toggleStayOnTop()
{
m_isStayOnTop = !m_isStayOnTop;
// 保存当前窗口位置和大小
QRect geometry = this->geometry();
// 更新窗口标志
Qt::WindowFlags flags = windowFlags();
if (m_isStayOnTop) {
flags |= Qt::WindowStaysOnTopHint;
} else {
flags &= ~Qt::WindowStaysOnTopHint;
}
// 应用新的窗口标志
setWindowFlags(flags);
// 恢复窗口位置和大小
setGeometry(geometry);
// 更新按钮状态
updateStayOnTopButton();
// 重新显示窗口
show();
}
// 处理置顶按钮点击
void NoteEditWidget::onStayOnTopClicked()
{
toggleStayOnTop();
}
// 更新置顶按钮状态
void NoteEditWidget::updateStayOnTopButton()
{
if (m_stayOnTopButton) {
m_stayOnTopButton->setChecked(m_isStayOnTop);
if (m_isStayOnTop) {
m_stayOnTopButton->setStyleSheet("QPushButton { background-color: #FFD700; border: 1px solid #CCCCCC; border-radius: 3px; padding: 3px; }"
"QPushButton:hover { background-color: #FFEB3B; }"
"QPushButton:pressed { background-color: #FFC107; }");
} else {
m_stayOnTopButton->setStyleSheet("QPushButton { background-color: white; border: 1px solid #CCCCCC; border-radius: 3px; padding: 3px; }"
"QPushButton:hover { background-color: #F0F0F0; }"
"QPushButton:pressed { background-color: #E0E0E0; }");
}
}
}
// 实现事件过滤器
bool NoteEditWidget::eventFilter(QObject *obj, QEvent *event)
{
if (obj == ui->contentTextEdit) {
if (event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
// 监听Ctrl+V组合键
if (keyEvent->matches(QKeySequence::Paste)) {
// 尝试从剪贴板插入图片
if (insertImageFromClipboard()) {
return true; // 事件已处理
}
// 如果没有图片,继续默认的粘贴操作
}
}
}
else if (obj == ui->contentTextEdit->viewport()) {
if (event->type() == QEvent::MouseButtonPress) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
QTextCursor cursor = ui->contentTextEdit->cursorForPosition(mouseEvent->pos());
// 检查光标位置是否在图片上
QTextCharFormat format = cursor.charFormat();
if (format.isImageFormat()) {
QTextImageFormat imageFormat = format.toImageFormat();
QString imagePath = imageFormat.name();
// 获取原始图片
QImage originalImage;
// 如果缓存了原始图片,从缓存获取
if (m_originalImages.contains(imagePath)) {
originalImage = m_originalImages[imagePath];
} else {
// 尝试从文件加载原图
QString localPath = imagePath;
if (imagePath.startsWith("file:///")) {
localPath = imagePath.mid(8);
}
if (QFile::exists(localPath)) {
originalImage.load(localPath);
// 缓存原始图片
m_originalImages[imagePath] = originalImage;
}
}
// 获取图片在文档中的位置和大小信息
QTextBlock block = cursor.block();
QTextBlock::iterator it;
// 查找图片在文本块中的位置
bool foundImage = false;
QRect imageRect;
for (it = block.begin(); it != block.end() && !foundImage; ++it) {
QTextFragment fragment = it.fragment();
if (fragment.isValid()) {
QTextCharFormat fragFormat = fragment.charFormat();
if (fragFormat.isImageFormat()) {
QTextImageFormat imgFormat = fragFormat.toImageFormat();
if (imgFormat.name() == imagePath) {
// 获取图片在文档中的位置
int fragmentPosition = fragment.position();
QTextCursor imgCursor(ui->contentTextEdit->document());
imgCursor.setPosition(fragmentPosition);
QRect imgRect = ui->contentTextEdit->cursorRect(imgCursor);
// 获取图片的宽高
int imgWidth = imgFormat.width();
int imgHeight = imgFormat.height();
// 构建图片的实际矩形区域
imageRect = QRect(imgRect.left(), imgRect.top(), imgWidth, imgHeight);
foundImage = true;
break;
}
}
}
}
// 如果找到了图片,并且点击位置在图片的实际区域内
if (foundImage) {
QPoint viewportPos = mouseEvent->pos();
if (imageRect.contains(viewportPos)) {
if (!originalImage.isNull()) {
// 显示图片查看器
showImageViewer(originalImage);
return true; // 事件已处理
}
}
}
// 如果点击位置不在图片的实际区域内,或者找不到图片,让事件继续传递,允许在图片周围编辑文本
return false;
}
}
else if (event->type() == QEvent::MouseMove) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
QTextCursor cursor = ui->contentTextEdit->cursorForPosition(mouseEvent->pos());
// 检查光标位置是否在图片上
QTextCharFormat format = cursor.charFormat();
if (format.isImageFormat()) {
QTextImageFormat imageFormat = format.toImageFormat();
QString imagePath = imageFormat.name();
// 获取图片在文档中的位置和大小信息
QTextBlock block = cursor.block();
QTextBlock::iterator it;
// 查找图片在文本块中的位置
bool foundImage = false;
QRect imageRect;
for (it = block.begin(); it != block.end() && !foundImage; ++it) {
QTextFragment fragment = it.fragment();
if (fragment.isValid()) {
QTextCharFormat fragFormat = fragment.charFormat();
if (fragFormat.isImageFormat()) {
QTextImageFormat imgFormat = fragFormat.toImageFormat();
if (imgFormat.name() == imagePath) {
// 获取图片在文档中的位置
int fragmentPosition = fragment.position();
QTextCursor imgCursor(ui->contentTextEdit->document());
imgCursor.setPosition(fragmentPosition);
QRect imgRect = ui->contentTextEdit->cursorRect(imgCursor);
// 获取图片的宽高
int imgWidth = imgFormat.width();
int imgHeight = imgFormat.height();
// 构建图片的实际矩形区域
imageRect = QRect(imgRect.left(), imgRect.top(), imgWidth, imgHeight);
foundImage = true;
break;
}
}
}
}
// 如果找到了图片,并且鼠标位置在图片的实际区域内
if (foundImage && imageRect.contains(mouseEvent->pos())) {
// 设置手型光标
ui->contentTextEdit->viewport()->setCursor(Qt::PointingHandCursor);
return true; // 事件已处理
} else {
// 恢复默认光标
ui->contentTextEdit->viewport()->setCursor(Qt::IBeamCursor);
}
} else {
// 恢复默认光标
ui->contentTextEdit->viewport()->setCursor(Qt::IBeamCursor);
}
}
}
return QWidget::eventFilter(obj, event);
}
// 获取编辑器可用宽度
int NoteEditWidget::getAvailableWidth()
{
// 获取编辑器的可用宽度(考虑内边距和滚动条)
return ui->contentTextEdit->viewport()->width() - 20; // 减去一些边距以提供更好的视觉效果
}
// 调整图片大小以适应窗口宽度
QImage NoteEditWidget::resizeImageToFitWidth(const QImage &image)
{
int availableWidth = getAvailableWidth();
// 获取设备像素比,考虑Windows的屏幕缩放
qreal devicePixelRatio = qApp->devicePixelRatio();
// 如果图片宽度超过可用宽度,则按比例缩放
if (image.width() > availableWidth) {
// 计算缩放后的实际像素尺寸,考虑设备像素比
int scaledWidth = availableWidth * devicePixelRatio;
int scaledHeight = (scaledWidth * image.height()) / image.width();
// 使用高质量缩放创建高清图像
QImage scaledImage = image.scaled(scaledWidth, scaledHeight,
Qt::KeepAspectRatio,
Qt::SmoothTransformation);
// 设置设备像素比,这样逻辑尺寸会自动调整
scaledImage.setDevicePixelRatio(devicePixelRatio);
return scaledImage;
}
// 如果图片实际尺寸不超过可用宽度,考虑设备像素比
// 当设备像素比不为1时,需要调整图片显示尺寸以匹配实际物理尺寸
if (devicePixelRatio > 1.0) {
// 创建一个新的图像,保持原始像素大小,但为QTextDocument标记正确的逻辑尺寸
QImage adjustedImage = image.copy();
adjustedImage.setDevicePixelRatio(devicePixelRatio);
return adjustedImage;
}
// 否则返回原图
return image;
}
// 将图片保存到文件
QString NoteEditWidget::saveImageToFile(const QImage &image, const QString &prefix)
{
// 确保图片目录存在
ensureImageDirectoryExists();
// 获取便签ID
int noteId = m_currentNote.id();
// 获取存储目录
QString dirPath = getImageDirectory(noteId);
QDir dir;
if (!dir.exists(dirPath)) {
dir.mkpath(dirPath);
}
// 生成唯一文件名
QString fileName = QString("%1_%2.png").arg(prefix).arg(QUuid::createUuid().toString(QUuid::WithoutBraces));
QString filePath = QString("%1/%2").arg(dirPath, fileName);
// 保存图片
image.save(filePath, "PNG");
// 保存原始图片到内存中,以便后续显示原图
m_originalImages[filePath] = image;
return filePath;
}
// 从剪贴板插入图片
bool NoteEditWidget::insertImageFromClipboard()
{
const QClipboard *clipboard = QApplication::clipboard();
const QMimeData *mimeData = clipboard->mimeData();
// 检查剪贴板是否包含图片
if (mimeData->hasImage()) {
QImage image = qvariant_cast<QImage>(mimeData->imageData());
if (!image.isNull()) {
// 保存原始图片
QImage originalImage = image;
// 获取设备像素比,处理Windows屏幕缩放问题
qreal devicePixelRatio = qApp->devicePixelRatio();
if (devicePixelRatio > 1.0) {
// 确保原始图像保持正确的设备像素比
originalImage.setDevicePixelRatio(1.0); // 重置为原始像素
}
// 调整图片大小
image = resizeImageToFitWidth(image);
// 保存图片到文件
QString filePath = saveImageToFile(originalImage, "clipboard");
// 生成资源名称
static int imageCounter = 0;
QString imageName = QString("clipboard_image_%1").arg(++imageCounter);
// 将调整后的图片添加到文档资源
ui->contentTextEdit->document()->addResource(
QTextDocument::ImageResource,
QUrl(filePath),
QVariant(image));
// 计算显示尺寸,考虑设备像素比
int displayWidth = image.width() / image.devicePixelRatio();
int displayHeight = image.height() / image.devicePixelRatio();
// 创建图片格式
QTextImageFormat imageFormat;
imageFormat.setName(filePath);
imageFormat.setWidth(displayWidth);
imageFormat.setHeight(displayHeight);
// 插入图片到光标位置
ui->contentTextEdit->textCursor().insertImage(imageFormat);
// 记录临时图片映射
m_tempImages[imageName] = filePath;
// 标记文档已修改
m_hasChanges = true;
m_autoSaveTimer->start();
return true;
}
}