QTextEdit ExtraSelection无法设置字体粗细

时间:2019-11-28 10:07:27

标签: qt fonts qt5 qtextedit

我无法通过QTextEdit中的ExtraSelection设置字体粗细(或相应的斜体样式)。

具有来自Nice text formatting in QTextEdit, like Qt Creator does的MSCCE的示例代码被盗, 我想问一下为什么这个例子中的字体粗细不加粗:

#include <QApplication>
#include <QtGui>
#include <QTextEdit>

int main(int argc, char *argv[])
{
  QApplication a(argc, argv);

  // create QTextEdit, with lot of text in it
  QTextEdit w("Alice and Bob (and Eve). ");
  for(int i=0;i<10;++i) w.setText(w.toPlainText() + w.toPlainText());

  // prepare variables for highlights
  QTextCharFormat fmt;
  fmt.setForeground(QBrush(Qt::GlobalColor::red));
  fmt.setFontWeight(QFont::Weight::Bold);
  //fmt.setUnderlineStyle(QTextCharFormat::SingleUnderline); // <- 1. this works
  //QBrush brush(Qt::BrushStyle::DiagCrossPattern); // <- 2. this works too!
  //fmt.setForeground(brush);


  // highlight all text in parenthesis
  QList<QTextEdit::ExtraSelection> selections;
  QTextCursor cursor = w.textCursor();
  while( !(cursor = w.document()->find(QRegExp("\\([^)]*\\)"), cursor)).isNull()) {
    QTextEdit::ExtraSelection sel = { cursor, fmt };
    selections.append(sel);
  }

  // set, show, go!
  w.setExtraSelections(selections);
  w.show();
  return a.exec();
}

https://doc.qt.io/qt-5/qtextedit-extraselection.html声明

  

一种用于为选择指定前景或背景画笔/颜色的格式。

setUnderlineStyle()(注释1)或设置画笔图案(注释2)有效。

对于它的价值,将QSyntaxHighlighter与setFontWeight()一起使用也可以。

使它起作用的诀窍是什么?

0 个答案:

没有答案