For a custom widget, there are tabs which ban be accessed with the ALT <C>
shortcut where <C>
can be any keyboard character key. In Qt, this is called a Mnemonic
For this shortcut, it is needed to have that letter underlined in the label.
I can see that QPainter::drawText
has an argument for flags, which can be provided with Qt::TextShowMnemonic
but I would like to have this while using QStaticText
for performance purpose. QStaticText allows Rich-Text, however underline seems not supported, or I could not make it work.
#include <QApplication>
#include <QDebug>
#include <QStaticText>
#include <QPainter>
#include <QPaintEvent>
#include <QWidget>
class TestWidget: public QWidget
{
Q_OBJECT
public:
explicit TestWidget( QWidget* parent=nullptr):QWidget(parent){}
auto paintEvent(QPaintEvent *event) -> void override
{
QPainter p(this);
QStaticText staticText; // this is not how it should be used, but for the example...
staticText.setTextFormat(Qt::TextFormat::RichText);
staticText.setText("<u>F</u>ile"); //What happens with Underline?
p.drawStaticText(QPoint(50,50), staticText);
p.drawText(QRect(50, 80, 100, 100), Qt::TextShowMnemonic, "&File"); // Ok, this works, but no static-text
}
};
#include "main.moc"
auto main (int argn, char* args[])-> int
{
QApplication app(argn, args);
qDebug() << QT_VERSION_STR;
TestWidget w;
w.resize(200,200);
w.show();
return app.exec();
}
Results in:
The question is:
How to make underline, or &mnemonic to work with QStaticText
?
.
CodePudding user response:
There seems to be a QT-BUG for this, almost 10 years old (it was created in 2012).
QStaticText doesn't support text-decoration css property.
Properties like font-weight, color, font-style do have an effect but the text-decoration does not. See the attached example program where is HTML string using a element to underline a part of the string. This doesn't seem to have any effect using .... Also when using just plain underline tags it doesn't work.There is also a conflict in the documentation of QStaticText concerning this issue stating that "For extra convenience, it is possible to apply formatting to the text using the HTML subset supported by QTextDocument.". However in the next chapter of the documention is said that "QStaticText can only represent text, so only HTML tags which alter the layout or appearance of the text will be respected. Adding an image to the input HTML, for instance, will cause the image to be included as part of the layout, affecting the positions of the text glyphs, but it will not be displayed. The result will be an empty area the size of the image in the output. Similarly, using tables will cause the text to be laid out in table format, but the borders will not be drawn."
It seems that the HTML subset supported by QTextDocument is not entirely applicable to QStaticText formatting.