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);
    ...
Community
  • 1
  • 1
Rinat
  • 1,941
  • 2
  • 17
  • 26
  • Saw that question, but I thought there are more simplier solution. And more native – Rinat Jun 22 '16 at 19:33
  • If you can use Qt 5.1, it looks like `addSection(const QString &)` might work. – Alyssa Haroldsen Jun 22 '16 at 19:35
  • Yes, it's most correct way :) But `addSection` displays only line too. read comments just now [there](http://stackoverflow.com/questions/22635903/non-interactive-items-in-qmenu#comment41418855_22647236). The problem is OS-specific (Win 7). Well, thank you for help! What to do with question now? – Rinat Jun 22 '16 at 19:46
  • Ah, I didn't see that. It seems the best bet might be a custom widget if it needs to work in Windows. – Alyssa Haroldsen Jun 22 '16 at 20:03

1 Answers1

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"));
Alexander V
  • 8,351
  • 4
  • 38
  • 47