[英]How to programmatically close QMenu
我有非常具體的情況。 我想將QAction
放入QToolbar
並達到以下行為:
QAction
。QDialog
應該出現在屏幕上,而不是QMenu
現在我對一起實現所有這些事情有點困惑。
現在我已經創建了QAction
,將它添加到工具欄,還創建了一個空的QMenu
,因為我不知道如何以另一種方式添加“下拉”箭頭。
因此,我還將我的插槽連接到QMenu
aboutToShow()
信號,現在,我可以在QMenu
顯示之前創建我的對話框並exec()
它。 但這里出現了主要問題:在我用我的對話框完成所有操作后,單擊OK
按鈕QMenu
試圖出現,但由於它是空的,它什么都不顯示,並且只有在我左鍵單擊某個位置以“關閉”此菜單后,進一步的操作才可用。
有什么方法可以強制QMenu
不顯示或可以從QMenu
繼承並重新實現其行為(我嘗試在從 QMenu 子類化之后使用QMenu
的exec()
show()
popup()
方法來做到這一點,但沒有一個當菜單出現在屏幕上時被調用)?
這是解決方案,對我有用。
class QCustomMenu : public QMenu
{
Q_OBJECT
public:
QCustomMenu(QObject *parent = 0):QMenu(parent){};
};
在代碼中:
QAction* myActionWithMenu = new QAction ( "ActionText", toolbar);
QCustomMenu* myMenu = new QCustomMenu(toolbar);
connect(myMenu, SIGNAL(aboutToShow()), this, SLOT(execMyMenu()));
execMyMenu()
實現:
void execMyMenu(){
m_activeMenu = (QCustomMenu*)sender(); // m_activeMenu -- private member of your head class, needs to point to active custom menu
QMyDialog* dlg = new QMyDialog();
// setup your dialog with needed information
dlg->exec();
// handle return information
m_myTimer = startTimer(10); // m_myTimer -- private member of your head(MainWindow or smth like that) class
}
現在我們必須處理 timerEvent 並關閉我們的菜單:
void MyHeadClass::timerEvent(QTimerEvent *event)
{
// Check if it is our "empty"-menu timer
if ( event->timerId()==m_myTimer )
{
m_activeMenu->close(); // closing empty menu
killTimer(m_myTimer); // deactivating timer
m_myTimer = 0; // seting timer identifier to zero
m_activeMenu = NULL; // as well as active menu pointer to NULL
}
}
它在每個平台上都運行良好,並且可以滿足我的需求。 希望,這會對某人有所幫助。 我花了一周的時間試圖找到這個解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.