QStyleOptionMenuItem draws a white straight line between the menu item's text and icon
-
I am trying to create a custom-looking menu item and for that I am using the QWidgetAction class. The goal is to have a menu action that looks exactly the same as an ordinary one, but also add a button with an icon on the right end which will configure the action's options. Thus, I have subclassed QWidgetAction and I have the following createWidget definition:
QWidget *createWidget(QWidget *parent) override { QMenu *parentMenu = qobject_cast<QMenu *>(parent); // Assume for simplicity that it is always a QMenu MenuItem *menuItem = new MenuItem(parentMenu, icon(), text(), "Ctrl+A"); QHBoxLayout *layout = new QHBoxLayout(); layout->setContentsMargins(0, 0, 0, 0); layout->setSpacing(0); layout->addWidget(menuItem, 20); QPushButton *optionsButton = new QPushButton(QIcon("../qtListApp/square.png"), QString()); layout->addWidget(optionsButton, 0); QWidget *container = new QWidget(parent); container->setLayout(layout); return container; }
And MenuItem inherits QWidget and looks exactly like a QMenu item. In order to achieve this, I have overriden the paintEvent method:
void paintEvent(QPaintEvent *event) override { QPainter painter(this); QStyleOptionMenuItem opt; opt.initFrom(this); opt.text = text; // This is passed via the constructor of MenuItem opt.menuItemType = QStyleOptionMenuItem::Normal; opt.icon = icon; // This is passed via the constructor of MenuItem opt.palette = parentMenu->palette(); opt.reservedShortcutWidth = fontMetrics().size(Qt::TextSingleLine, shortcutText).width(); if(rect().contains(mapFromGlobal(QCursor::pos()))) { opt.state |= QStyle::State_Selected; } style()->drawControl(QStyle::CE_MenuItem, &opt, &painter, this); }
And everything looks good, apart from the following straight white line defect between the icon and text:
What could cause this? Thanks in advance
-
@mrjj
I have the following stylesheet applied to a containing widgetQMenu, QMenu QPushButton { background-color: #303030; color: white }
When I remove the QMenu selector, the white line disappears (hence it starts looking like this)
I cannot say whether the white line really disappears or it just blends with the white color of the menu item.
After applying the same style with a QMenu::item selector, I get the following:
The ordinary menu items are colored, but those created by my class are not. It appears as if the ::menuItem selector does not work on them.
I also tried setting the following style rule on the container returned by the createWidget function
container->setStyleSheet(".MenuItem {background-color: #303030; color: white; }");
and it oddly makes the custom menu items get shifted to the left and the hover effects on them do not seem to work any longer. Applying padding/margin does not fix it: