Roson讲Qt #1 QTextEdit
目录
1.设置文本
2.获取文本
3.文本修改事件
4.文本选择事件(光标移动时也会出发)
5.获取光标后的文本
6.获取光标前的文本
7.获取光标所在的行号
8.获取光标所在的列号
9.设置自动换行模式
10.设置字体颜色
方法1
方法2
方法3
方法4
11.设置背景色
方法1
方法2
方法3
12.设置字体
13.改变任意位置部分字符的颜色
14.选中任意位置任意长度的字符
15.设置html格式的文本
1.设置文本
ui.textEdit->setText("Hello world");
2.获取文本
qDebug()<<ui.textEdit->toPlainText();
3.文本修改事件
public slots:
void OnTextChanged();
...
connect(ui.textEdit,SIGNAL(textChanged()),this,SLOT(OnTextChanged()));
4.文本选择事件(光标移动时也会出发)
public slots:
void OnSelectionChanged();
...
connect(ui.textEdit, SIGNAL(selectionChanged()), this, SLOT(OnSelectionChanged()));
5.获取光标后的文本
int charIndex = ui.textEdit->textCursor().position();
QString strText = ui.textEdit->toPlainText().mid(charIndex);
qDebug() << "Text After Cursor:" << strText << "\n";
6.获取光标前的文本
int charIndex = ui.textEdit->textCursor().position();
strText = ui.textEdit->toPlainText().left(charIndex);
qDebug() << "Text before Cursor:" << strText << "\n";
7.获取光标所在的行号
int rowNo = ui.textEdit->textCursor().blockNumber();
8.获取光标所在的列号
int colNo = ui.textEdit->textCursor().columnNumber();
9.设置自动换行模式
ui.textEdit->setWordWrapMode(QTextOption::NoWrap);
Qt提供了下面几种换行模式,根据需要选择
QTextOption::NoWrap | 0 | 文本完全没有换行。 |
QTextOption::WordWrap | 1 | 文本在单词边界处换行。 |
QTextOption::ManualWrap | 2 | 和NoWrap一样。 |
QTextOption::WrapAnywhere | 3 | 文本可以在一行中的任何点换行,即使它出现在单词的中间。 |
QTextOption::WrapAtWordBoundaryOrAnywhere | 4 | 如果可能,换行发生在单词边界;否则,它将出现在行中适当的点,甚至在单词的中间。 |
10.设置字体颜色
方法1
QPalette palete;
palete.setColor(QPalette::Text,Qt::red);
ui.textEdit->setPalette(palete);
方法2
ui.textEdit->setTextColor(QColor("blue"));
ui.textEdit->append("4564564646");
方法3
ui.textEdit->setStyleSheet("color:rgb(80,240,120)");
ui.textEdit->append("ppppad");
方法4
QTextCharFormat format;
format.setForeground(QBrush("red"));
ui.textEdit->mergeCurrentCharFormat(format);
ui.textEdit->append("abcdefgla");
其中方法2和方法4在编辑框无任何字符时使用,将不会生效。只有等编辑框上面有了字符之后,再用才会有效果。
11.设置背景色
方法1
ui.textEdit->setStyleSheet("background-color:rgb(80,240,120)");
ui.textEdit->append("ppppad");
方法2
QTextCharFormat format;
format.setBackground(QBrush("red"));
ui.textEdit->mergeCurrentCharFormat(format);
ui.textEdit->append("abcdefgla");
方法3
QPalette palete;
palete.setColor(QPalette::Base, Qt::red);
ui.textEdit->setPalette(palete);
ui.textEdit->append("ppppad");
12.设置字体
ui.textEdit->setFont(QFont("Times", 20, QFont::Bold));
13.改变任意位置部分字符的颜色
QTextCharFormat format;
format.setForeground(QBrush("red"));
QTextCursor cursor = ui.textEdit->textCursor();
cursor.setPosition(0, QTextCursor::MoveAnchor);
cursor.setPosition(5, QTextCursor::KeepAnchor);
cursor.mergeCharFormat(format);
14.选中任意位置任意长度的字符
QTextCursor cursor = ui.textEdit->textCursor();
cursor.setPosition(5, QTextCursor::MoveAnchor);
cursor.setPosition(10, QTextCursor::KeepAnchor);
ui.textEdit->setTextCursor(cursor);
15.设置html格式的文本
ui.textEdit->setHtml("<i>This text is italic</i>");
还没有评论,来说两句吧...