天天看點

Qt之自定義菜單(右鍵菜單)

在接觸Qt這段時間以來,經常遇到菜單項的問題(右鍵菜單、托盤菜單、按鈕菜單等),QMenu用于菜單欄,上下文菜單,彈出菜單等,利用QMenu+QAction就可以達到效果!

右鍵菜單實作:通過重寫contextMenuEvent(QContextMenuEvent *event)事件,QMenu+QAction即可完美實作!

對象:QTreeWidget      
void ImageTree::createActions()
{

    //建立菜單、菜單項

    pop_menu = new QMenu();

    add_images_action = new QAction(this); 

    add_folder_action = new QAction(this);

    remove_selected_action = new QAction(this);

    remove_all_action = new QAction(this);



    //連接配接信号與槽

    connect(add_images_action, &QAction::triggered, this, &ImageTree::selectImages);

    connect(add_folder_action, &QAction::triggered, this, &ImageTree::selectFolder);

   connect(remove_selected_action, &QAction::triggered, this, &ImageTree::removeSelectedImages);

    connect(remove_all_action, &QAction::triggered, this, &ImageTree::removeAllImages);

}



void ImageTree::contextMenuEvent(QContextMenuEvent *event)

{

    //清除原有菜單

    pop_menu->clear();

   pop_menu->addAction(add_images_action);

   pop_menu->addAction(add_folder_action);

   pop_menu->addAction(remove_selected_action);

   pop_menu->addAction(remove_all_action);



    //菜單出現的位置為目前滑鼠的位置

   pop_menu->exec(QCursor::pos());

    event->accept();

}



void ImageTree::translateLanguage()

{

   add_images_action->setText(tr("add images"));

   add_folder_action->setText(tr("add folder"));

   remove_selected_action->setText(tr("remove selected images"));

   remove_all_action->setText(tr("remove all images"));

}      

繼續閱讀