Qt 自定义菜单、右键菜单

在接触Qt这段时间以来,经常遇到菜单项的问题(右键菜单、托盘菜单、按钮菜单等),QMenu用于菜单栏,上下文菜单,弹出菜单等,利用QMenu+QAction就可以达到效果!

右键菜单实现:通过重写contextMenuEvent(QContextMenuEvent *event)事件,QMenu+QAction即可完美实现!

对象:QTreeWidget

实现方式:createActions用于创建菜单、菜单项,contextMenuEvent用于实现菜单的显示,translateLanguage用于实现菜单的文本(此方法主要设置多语化使用)

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"));
}

 Qt 自定义菜单、右键菜单_第1张图片

二级菜单的实现(包括三级菜单或者更多)也类似,只需要使用QMenu的addMenu()方法即可! 

你可能感兴趣的:(Qt,界面设置,qt,开发语言)