QTextEdit

main.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
#include <QTextEdit>
#include <QVBoxLayout>
#include <QPushButton>
#include <QLabel>
#include <qapplication.h>

void setupTextEditDemo(QWidget *parent) {
QVBoxLayout *layout = new QVBoxLayout(parent);

// --- 1. 创建多行文本框 ---
QTextEdit *textEdit = new QTextEdit(parent);
textEdit->setPlaceholderText("请输入详细描述内容(支持 HTML 标签)...");

// 设置一些初始内容
textEdit->setPlainText("这是一段纯文本初始内容。");

// --- 2. 控制按钮:插入 HTML 内容 ---
QPushButton *btnHtml = new QPushButton("插入红色加粗文字", parent);
QObject::connect(btnHtml, &QPushButton::clicked, [textEdit]() {
// append 是在末尾追加,insertHtml 是在光标处插入
textEdit->insertHtml("<b style='color:red;'> [新内容] </b>");
});

// --- 3. 统计字数的标签 ---
QLabel *countLabel = new QLabel("当前字数:10", parent);

// --- 4. 信号:textChanged ---
// 注意:QTextEdit 的 textChanged() 信号不带参数,需要手动获取文本
QObject::connect(textEdit, &QTextEdit::textChanged, [textEdit, countLabel]() {
// toPlainText() 获取不带格式的纯文字
QString content = textEdit->toPlainText();
countLabel->setText(QString("当前字数:%1").arg(content.length()));
});

// --- 5. 清空按钮 ---
QPushButton *btnClear = new QPushButton("清空全部", parent);
QObject::connect(btnClear, &QPushButton::clicked, [textEdit]() {
textEdit->clear();
});

layout->addWidget(new QLabel("多行编辑器:"));
layout->addWidget(textEdit);
layout->addWidget(countLabel);
layout->addWidget(btnHtml);
layout->addWidget(btnClear);
}
int main(int argc, char *argv[]) {
QApplication a(argc, argv);

QWidget w;
w.setWindowTitle("QLineEdit 深度测试");
w.resize(400, 300);

// 调用我们的函数
setupTextEditDemo(&w);

w.show();
return a.exec();
}