Search code examples
qtqmenuqaction

Why QMenu's separator doesn't show text?


My goal is to make menu with labeled separators. So, I am running this code:

QMenu *menu = new QMenu;

QAction *group1 = menu->addSeparator();
group1->setText("Group of actions #1");
menu->addAction("Action #1");
menu->addAction("Action #2");
menu->addAction("Action #3");

QAction *group2 = menu->addSeparator();
group2->setText("Group of actions #2");
menu->addAction("Action #1");
menu->addAction("Action #2");
menu->addAction("Action #3");

QToolButton btn;
btn.setText("Click me");
btn.setMenu(menu);
btn.setPopupMode(QToolButton::InstantPopup);

btn.show();

and got this

QMenu's separator text not shown

instead of this (I created it by MS Paint :) )

enter image description here

What's wrong?

EDIT: Yes, there are another question like this (Non interactive items in QMenu), but maybe more simplier way exists?

One of solutions is using "Fusion" theme :) I just added code below into int main function:

int main(int argc, char *argv[]) {
    QApplication::setStyle("Fusion");
    QApplication a(argc, argv);
    ...

Solution

  • I need a text styled separator for my Qt menu. How can I do that?

    I resolve the problem like that:

    QWidgetAction* MyWidget::createTextSeparator(const QString& text)
    {
        auto* pLabel = new QLabel(text);
        pLabel->setMinimumWidth(this->minimumWidth() - 4);
        // grayish style
        pLabel->setStyleSheet("background: #FF4B4B4B;");
        // possible alignment
        // pLabel->setAlignment(Qt::AlignCenter);
        auto* separator = new QWidgetAction(this);
        separator->setDefaultWidget(pLabel);
        return separator;
    }
    
    pMenu->addAction(createTextSeparator("Group of actions"));