3131#include < QVBoxLayout>
3232#include < QSpacerItem>
3333#include < QLabel>
34+ #include < QRegularExpression>
3435
3536NoteEditWidget::NoteEditWidget (QWidget *parent) :
3637 QWidget(parent),
@@ -213,11 +214,18 @@ void NoteEditWidget::setupUI()
213214
214215 // 更新置顶按钮状态
215216 updateStayOnTopButton ();
217+
218+ // 获取字数统计标签指针
219+ m_wordCountLabel = findChild<QLabel*>(" wordCountLabel" );
220+ if (m_wordCountLabel) {
221+ m_wordCountLabel->setText (" 字数:0" );
222+ }
216223}
217224
218225void NoteEditWidget::setupConnections ()
219226{
220227 connect (ui->contentTextEdit , &QTextEdit::textChanged, this , &NoteEditWidget::onContentChanged);
228+ connect (ui->contentTextEdit , &QTextEdit::textChanged, this , &NoteEditWidget::updateWordCount);
221229 connect (ui->titleLineEdit , &QLineEdit::textChanged, this , &NoteEditWidget::onTitleChanged);
222230 connect (ui->boldButton , &QPushButton::clicked, this , &NoteEditWidget::onBoldButtonClicked);
223231 connect (ui->italicButton , &QPushButton::clicked, this , &NoteEditWidget::onItalicButtonClicked);
@@ -354,6 +362,9 @@ void NoteEditWidget::setNote(const Note ¬e)
354362 }
355363
356364 activateWindow (); // 确保窗口获得焦点
365+
366+ // 更新字数统计
367+ updateWordCount ();
357368}
358369
359370void NoteEditWidget::createNewNote ()
@@ -401,6 +412,9 @@ void NoteEditWidget::createNewNote()
401412 }
402413
403414 activateWindow (); // 确保窗口获得焦点
415+
416+ // 更新字数统计
417+ updateWordCount ();
404418}
405419
406420Note NoteEditWidget::getCurrentNote () const
@@ -1501,4 +1515,34 @@ bool ImageEventFilter::eventFilter(QObject *watched, QEvent *event)
15011515 }
15021516
15031517 return QObject::eventFilter (watched, event);
1518+ }
1519+
1520+ void NoteEditWidget::updateWordCount ()
1521+ {
1522+ if (!m_wordCountLabel) return ;
1523+ // 获取正文纯文本内容
1524+ QString text = ui->contentTextEdit ->toPlainText ();
1525+ int count = 0 ;
1526+ // 统计汉字数量
1527+ QRegularExpression hanziRe (" [\u4e00 -\u9fa5 ]" );
1528+ QRegularExpressionMatchIterator it = hanziRe.globalMatch (text);
1529+ while (it.hasNext ()) {
1530+ it.next ();
1531+ ++count;
1532+ }
1533+ // 统计英文单词数量
1534+ QRegularExpression wordRe (" [A-Za-z]+(?:'[A-Za-z]+)?" );
1535+ it = wordRe.globalMatch (text);
1536+ while (it.hasNext ()) {
1537+ it.next ();
1538+ ++count;
1539+ }
1540+ // 统计数字串数量(每个连续数字串算一个字)
1541+ QRegularExpression numRe (" \\ d+" );
1542+ it = numRe.globalMatch (text);
1543+ while (it.hasNext ()) {
1544+ it.next ();
1545+ ++count;
1546+ }
1547+ m_wordCountLabel->setText (QString (" 字数:%1" ).arg (count));
15041548}
0 commit comments