I have been having problems adding a menu item to the built in menu bar in a Qt desktop application. I copied the code provided in the QMainWindow class reference documentat
menu = self.menuBar()
menu.setNativeMenuBar(False)
I know its late by 4 yrs, but i ran into same issue & spotted this on the Qt forum for ubuntu/Mac OS.
https://forum.qt.io/topic/7276/menu-not-showing-up-in-menubar/15
Add the following to your main.cpp before you declare your Mainwindow w:
QCoreApplication::setAttribute(Qt::AA_DontUseNativeMenuBar);
In my case my main.cpp file now looks like:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
AddressBook addressBook;
AddressBookController controller (&addressBook);
QCoreApplication::setAttribute(Qt::AA_DontUseNativeMenuBar); //fix for menubar notshowing in ubuntu
MainWindow w(&controller);
w.show();
return a.exec();
}
In order for OS X to gain control over the menu bar, you need to create the menu bar without a parent widget. This means in the mainwindow.cpp
file typically, you'd have to create your menu bar in code.
This is my code that also puts in the About and Preferences menu items in the PROGRAM menu drop down as is standard on a mac:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
this->aboutAction = new QAction(0);
this->aboutAction->setMenuRole(QAction::AboutRole);
this->aboutWindow = new About();
this->preferencesAction = new QAction(0);
this->preferencesAction->setMenuRole(QAction::PreferencesRole);
this->preferencesWindow = new Preferences();
this->mainMenuBar = new QMenuBar(0); // 0 explicitly states to create it with no parent
this->mainMenu = new QMenu(0); // Same here
this->mainMenuBar->addMenu(this->mainMenu);
this->mainMenu->addAction(this->aboutAction);
this->mainMenu->addAction(this->preferencesAction);
this->setMenuBar(this->mainMenuBar);
// ...
}
Preferences
and About
are classes that handle their respective windows and code isn't included.
You will need to remove the menu bar in the mainwindow ui form that gets automatically generated.
It's pretty old Qt bug on OS X. You can work with QMenu and QMenuBar by calling QMenuBar::addAction, QMenuBar::removeAction and QMenuBar::insertAction. The trick is done by calling of QMenu::menuAction method.
Check the code below:
QMenu *menu = new QMenu("First menu");
menu->addAction("item 1");
menu->addAction("item 2");
m_menuBar->addAction(menu->menuAction());
Also you can check my another answer here with code snippet ready to compile and run.
The answer that has the most upvote works for Python, but question is for C++. However, the method is the same.
You can add this line on top of your constructor in mainwindow.cpp:
menuBar()->setNativeMenuBar(false);
I had same issued in ubuntu with python
I used menubar's setNativeMenubar method. You can find this in c++ pyqt docs.
menu = self.menuBar()
menu.setNativeMenuBar(False)