I am attempting to add an icon to my QMenu using Qt Designer, however I realized that my text disappears when my icon is added. Is there any way for me to show my icon next to my text?
It was not supported in Qt 4, maybe it is in Qt5 I haven't checked. In Designer itself there isn't much you can do. In the code one option is to customize the style to draw both the icon and text: - sizeFromContents for QStyle::CT_MenuBarItem - drawControl for QStyle::CE_MenuBarItem - drawCustomControl for QStyleOptionMenuItem
ui->menuMyQMenu
? –
Labe This is not supported by default, mostly because it is not usual an operation that you wish to achieve in here. Of course, you could always use an image with text included, but that is also hackish, unless you paint the image dynamically and then load it later. Although even that would be quite a bit of work.
In order to do, you will need to fiddle with Qt a bit. This is the closest experiment that I would start off with, personally. I have not had time to check whether it actually works, but there should be something among these lines:
class CustomMenuBarWidget : public QWidget
{
public:
explicit CustomMenuBarWidget(QWidget *parent = Q_NULLPTR)
: QWidget(parent)
, menuBar(new QMenuBar())
{
}
virtual void paintEvent(QPaintEvent *event) {
QStyleOptionMenuItem styleOptionMenuItem;
QIcon icon("path/to/my/icon");
styleOptionMenuItem.icon = icon;
styleOptionMenuItem.text = "Hello World!";
QPainter painter(this);
menuBar->style()->drawControl(QStyle::CE_MenuBarItem, &styleOptionMenuItem, &painter, menuBar);
}
private:
QMenuBar *menuBar;
};
You could probably also have a look at QWidgetAction how to insert custom widgets into toolbars and menubars. I have never used that myself in any serious project, but might be useful to be aware of.
© 2022 - 2024 — McMap. All rights reserved.
File
and if I add an icon to it the textFile
disappears and only the icon is present – HamzaTextBesideIcon
,IconOnly
... like inQToolButton
. – ArniQMenu->style
fromIconOnly
toTextBesideIcon
. I understand that a reimplementation ofQMenu
is too much to ask and did not expect that to be necessary. As a workaround I used an icon-only-menu and a text-only-menu next to each other with the same content. People do not seem to care about the difference. 500 is almost a third of my hard earned rep, you do it ;D – Labe