我可以使用简单的 html 设置单行大小的 QTextEdit 吗?

Can I have single line sized QTextEdit with simple html?

我需要使用包含以下样式的文本显示简单的状态行:

QTextEdit 可以呈现简单 HTML。但它也强行扩展到多行:

添加了红色背景以强调 QTextEdit 的尺寸。所需大小是一个文本行的大小。我该如何实现?

如果您想要文本行的大小,请使用 QFontMetrics

QTextEdit* textEdit = new QTextEdit();
QFontMetrics metrics(textEdit->font());
int lineHeight = metrics.lineSpacing();
textEdit->setFixedHeight(lineHeight);

如果不够,您可以在 lineHeight 中添加一两个像素。

也许简单的解决方案是使用 QWidget class 的 setFixedHeight 方法(Qt 文档:http://doc.qt.io/qt-5/qwidget.html#setFixedHeight

yourTextEdit->setFixedHeight(/*Height for one text line*/);

首先,如果您只是简单地使用了 QLabel,则不需要做任何特殊的事情:它支持富文本格式,并且只需要尽可能多的 space :

#include <QtWidgets>
int main(int argc, char ** argv) {
   QApplication app{argc, argv};
   QWidget w;
   QVBoxLayout layout{&w};
   QLineEdit edit;
   QLabel message{"Foo <font color=\"red\">Bar!</font>"};
   message.setTextFormat(Qt::RichText);
   message.setWordWrap(true);
   message.setFrameStyle(QFrame::Box);
   layout.addWidget(&edit);
   layout.addWidget(&message);
   layout.addStretch();
   QObject::connect(&edit, &QLineEdit::textChanged, &message, &QLabel::setText);
   w.show();
   return app.exec();
}

如果您坚持使用 QTextEdit:它包含一个 QTextDocument,由其 documentLayout() 布局。每次布局大小发生变化时,布局都会发出一个信号。您可以对该信号采取行动以更改小部件的高度以适应文档的大小。考虑 QTextEdit 的结构:它是 QAbstractScrollArea 并且内容显示在 viewport() 小部件中。目标是 viewport() 足够大以适合文本文档。小部件本身可能更大,具体取决于活动样式或样式 sheet.

下面是您如何实现它的示例。行编辑的内容传播到只读 message QTextEdit,因此您可以注意到当文本太长而无法容纳在一行中时,小部件大小是如何实时更新的.当您更改小部件的宽度时,这会自动更新大小,因为文档大小也会因高度与宽度的权衡而发生变化。

// https://github.com/KubaO/Whosebugn/tree/master/questions/textedit-height-37945130
#include <QtWidgets>

void updateSize(QTextEdit * edit) {
   auto textHeight = edit->document()->documentLayout()->documentSize().height();
   edit->setFixedHeight(textHeight + edit->height() - edit->viewport()->height());
}

int main(int argc, char ** argv) {
   QApplication app{argc, argv};
   QWidget w;
   QVBoxLayout layout{&w};
   QLineEdit edit;
   QTextEdit message;
   message.setReadOnly(true);
   message.setText("Foo Bar!");
   layout.addWidget(&edit);
   layout.addWidget(&message);
   layout.addStretch();
   QObject::connect(&edit, &QLineEdit::textChanged, &message, &QTextEdit::setPlainText);
   QObject::connect(message.document()->documentLayout(),
                    &QAbstractTextDocumentLayout::documentSizeChanged,
                    &message, [&]{ updateSize(&message); });
   w.show();
   return app.exec();
}

您可以像这样创建和初始化文本框:

QTextEdit* te = new QTextEdit ("0");
te->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
te->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
te->setLineWrapMode(QTextEdit::NoWrap);
te->setFixedHeight(50);

关键的属性是setLineWrapMode,我已经设置为NoWrap

您可以使用 QLineEdit。我不确定它是否是最近添加的。