Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a signal to a QMenu instead of QAction in Qt?

I would like to have a menu item without children. I have a QMenubar, and in this menubar there is a QMenu. To use it as a menu, I have to put QActions in it, and they will appear if I click on the QMenu. How is it possible, to have only the menu, without any QActions, to do an action just as if it were a QAction?

A workaround would be to have a toolbox and disguise it as a menu, but it raises several problems:

  • It's not the cleanest solution
  • I have to manually care about highlighting it on mouse hover, and it will not be platform- and user setting independent.
  • I can't use it together in a menubar with normal menus with children.
like image 212
vsz Avatar asked Oct 11 '22 18:10

vsz


1 Answers

So you want a menu bar that triggers actions without opening sub-menus?

Try to directly add QActions to the menubar, instead of having a QMenu inbetween:

#include <QtWidgets>

int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QMainWindow *wnd = new QMainWindow;
    QMenuBar *m = new QMenuBar;
    QAction *a = new QAction("DoIt");

    QObject::connect(a, &QAction::triggered, [wnd](){
        QMessageBox::information(wnd, "DoIt", "DoIt");
    });

    m->addAction(a);
    wnd->setMenuBar(m);
    wnd->show();
    return app.exec();
}

Alternatively, you could subclass the QMenu and handle the mousePressEvent method to emit a signal

like image 166
king_nak Avatar answered Oct 31 '22 22:10

king_nak