Why QMenu's separator doesn't show text? [duplicate]
Asked Answered
J

1

6

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);
    ...
Joliejoliet answered 22/6, 2016 at 19:28 Comment(4)
Saw that question, but I thought there are more simplier solution. And more nativeJoliejoliet
If you can use Qt 5.1, it looks like addSection(const QString &) might work.Phospholipide
Yes, it's most correct way :) But addSection displays only line too. read comments just now there. The problem is OS-specific (Win 7). Well, thank you for help! What to do with question now?Joliejoliet
Ah, I didn't see that. It seems the best bet might be a custom widget if it needs to work in Windows.Phospholipide
A
5

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"));
Armourer answered 22/6, 2016 at 21:36 Comment(1)
This answer belongs to the original question.Marrufo

© 2022 - 2024 — McMap. All rights reserved.