Issue
I would like to ask, if it is possible to add some text onto QToolBar
with Qt Designer?
Solution
You could do it in Qt Designer, but it’d be a bad hack an unnecessary. Instead, do it via code. There are two ways:
-
QToolBar
is a widget that graphically represents actions, represented byQAction
. You can add an action that is pure text, using theQToolBar::addAction(const QString &)
. E.g. if the toolbar object is simply calledtoolbar
, you’d writetoolbar->addAction("Some text");
. This will create a button with given text, and return the corresponding action. Actions are an abstraction: they are devoid of a graphical representation, and they can be a part of multiple widgets (e.g. menus and toolbars). It’s the individual widgets that give the actions some "physical shape", e.g. construct a button for each action. -
QToolBar
, at a lower level, is a collection of widgets, that you can add usingQToolBar::addWidget(QWidget *)
. So, if you want to add some static text, you’d create a label with that text and add it to the toolbar. The action thus created may not seem very useful, since you won’t be reacting to the user clicking the text (see p.1 above if you do). But it could be used to show and hide the text if desired, and acts as a handle for the text, allowing you to change the text as well. It is really aQWidgetAction
derived class. See below for some code to get you started.
// The text can be empty, in case it was meant to be set sometime later
QAction *addText(QToolBar *toolbar, const QString &text = {})
{
auto *const label = new QLabel;
auto *const action = toolbar->addWidget(label);
// Any changes to the action's text should be propagated to the label.
QObject::connect(action, &QAction::changed, label, [action,label]{
label->setText(action->text());
});
action->setParent(toolbar); // so that the action won't leak
action->setText(text);
action->setVisible(true);
return action;
}
// inside some method
auto *action = addText(toolbar, "Some text");
// sometime later
action->setText("Some other text");
A more flexible way of doing this would be to derive QWidgetAction
to create e.g. StaticTextAction
, and put the label creation code into StaticTextAction::createWidget()
. But such flexibility is most likely unnecessary, since all you’re after here is some static text that applies to the toolbar and has no other use (e.g. you wouldn’t add it to any other widgets or menus).
Answered By – Kuba hasn't forgotten Monica
Answer Checked By – Marilyn (BugsFixing Volunteer)