Qt在Mac OSX下的系統菜單添加

標題:Qt在Mac OSX下的系統菜單添加
頭文件:#include <QMenuBar>
方法:
QAction minAction = new QAction(tr("Min"), this);
minAction->setShortcut(QKeySequence(tr("Ctrl+M")));
QAction maxAction = new QAction(tr("Max"), this);
maxAction->setShortcut(QKeySequence(tr("Ctrl+W")));

//1. 獲取菜單欄
QMenuBar menuBar = new QMenuBar(0);
//2. 給菜單欄添加菜單
QMenu *wnd = menuBar->addMenu(tr("Window"));
//3. 給菜單添加菜單項
wnd->addAction(m_minAction);
wnd->addSeparator();
wnd->addAction(m_maxAction);

可以繼續給menuBar添加更多菜單:QMenu *tmp=menuBar->addMenu(...),
然後給菜單tmp添加更多項:tmp->addAction(...),
或者用tmp->addSeparator()可以給菜單添加一個分界線。
Qt幫助對添加菜單的描述如下:
QMenuBar *QMainWindow::menuBar() const
Returns the menu bar for the main window. This function creates and returns an empty menu bar if the menu bar does not exist.
If you want all windows in a Mac application to share one menu bar, don't use this function to create it, because the menu bar created here will have this QMainWindow as its parent. Instead, you must create a menu bar that does not have a parent, which you can then share among all the Mac windows. Create a parent-less menu bar this way:

QMenuBar *menuBar = new QMenuBar(0);

因此,一般會用QMenuBar(0)構造一個沒有父窗口的菜單欄,而QMainWindow::menuBar()函數會構造一個
基於QMainWindow爲父的菜單欄。
QAction的setShortcut(QKeySequence(tr("Ctrl+M")))會創建快捷鍵“Ctrl+M”進行響應該菜單項的點擊,
用信號槽進行連接,比如:
QObject::connect(m_minAction, SIGNAL(triggered()), this, SLOT(onMinClicked()));
這樣在按下響應快捷鍵或用鼠標點擊菜單項時,會調用相應的槽函數,如:onMinClicked()函數。

效果如下:

注意:1. Mac OSX下在設快捷鍵時,Ctrl、Qt::CTRL等的Ctrl都指的是command鍵,而Qt::Key_Meta才
值得是鍵盤上的control鍵[具體應用可以查看Qt的幫助文檔]。而且此快捷鍵不能與系統預設的快捷鍵衝突,否則以系統預設優先。
另外,如果Qt的控件有接收按鍵事件(如QML中的Keys.onPressed)且該控件被激活,則設置的快捷鍵
也會失效,會優先調用控件的按鈕事件。
   2. Mac的系統菜單在應用啓動時會默認出現的桌面的左上角,第一項爲以應用名爲菜單的項,主要
依據Mac下每個應用的Info.plist文件,他裏面有個<key>CFBundleName</key> <string>appName</string>
進行確定,第一個菜單項顯示的是appName,其國際化通過Info.plist的<key>CFBundleDevelopmentRegion</key> <string>English/China</string>
進行確定。

踩過的坑:
在Qt的槽函數中不能對代碼進行平臺宏的控制,否則,在發送信號轉到槽函數時不能正常響應。
例如如下槽函數:
public slots:
#ifndef _WIN32_
void onSlotFunc();
#endif
        這樣即使你用QObject::connect(sender, SIGNAL(signalFunc()), reciver, SLOT(onSlotFunc));鏈接了信號槽,
當發送信號emit signalFunc()時,是不能轉到槽函數onSlotFunc()的。
發佈了58 篇原創文章 · 獲贊 83 · 訪問量 23萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章