Qt如何按字符更改选定的文本字符
Qt How to change selected text char by char
我正在 Qt 中创建一个简单的文本编辑器。
我能够编辑 selected 文本并使其成为粗体或下划线或两者兼而有之。问题是 selected 文本是部分粗体、正常或其他。
所以让它变得更好的唯一方法是采用 selected 文本并逐个字符地编辑它(如果它已经是草书并且我也希望它是粗体,则字符必须是两者)。
这是我的代码的一部分,我可以在其中将 selected 文本更改为粗体:
QFont font;
QTextCursor cursor = ui->textEdit->textCursor();
QTextCharFormat format;
if(cursor.hasSelection()){
font = cursor.charFormat().font();
if(!cursor.charFormat().font().bold()){
font.setBold(true);
format.setFont(font);
cursor.setCharFormat(format);
}
else{
font.setBold(false);
format.setFont(font);
cursor.setCharFormat(format);
}
ui->textEdit->setTextCursor(cursor);
草书功能相同。
这不适用于已编辑的文本。
示例:
randomtext
现在我想 select 部分文本,例如:"ndomte" 并全部加粗。我的结果是:
randomtext
我想要的是:
randomtext
我该怎么做?
也许你可以使用 QTextCursor::mergeCharFormat(const QTextCharFormat & modifier)
? http://doc.qt.io/qt-5/qtextcursor.html#mergeCharFormat
示例:
QTextCharFormat format;
format.setFontWeight(QFont::Bold);
cursor.mergeCharFormat(format);
我正在 Qt 中创建一个简单的文本编辑器。
我能够编辑 selected 文本并使其成为粗体或下划线或两者兼而有之。问题是 selected 文本是部分粗体、正常或其他。
所以让它变得更好的唯一方法是采用 selected 文本并逐个字符地编辑它(如果它已经是草书并且我也希望它是粗体,则字符必须是两者)。
这是我的代码的一部分,我可以在其中将 selected 文本更改为粗体:
QFont font;
QTextCursor cursor = ui->textEdit->textCursor();
QTextCharFormat format;
if(cursor.hasSelection()){
font = cursor.charFormat().font();
if(!cursor.charFormat().font().bold()){
font.setBold(true);
format.setFont(font);
cursor.setCharFormat(format);
}
else{
font.setBold(false);
format.setFont(font);
cursor.setCharFormat(format);
}
ui->textEdit->setTextCursor(cursor);
草书功能相同。
这不适用于已编辑的文本。
示例:
randomtext
现在我想 select 部分文本,例如:"ndomte" 并全部加粗。我的结果是:
randomtext
我想要的是:
randomtext
我该怎么做?
也许你可以使用 QTextCursor::mergeCharFormat(const QTextCharFormat & modifier)
? http://doc.qt.io/qt-5/qtextcursor.html#mergeCharFormat
示例:
QTextCharFormat format;
format.setFontWeight(QFont::Bold);
cursor.mergeCharFormat(format);