Qt_自定义菜单

一、右键菜单

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

重写voidcontextMenuEvent(QContextMenuEvent*event)事件

void Form::contextMenuEvent(QContextMenuEvent *event)
{
    //创建菜单、菜单项
    QMenu *pop_menu = new QMenu();
    QAction *add_images_action = new QAction(this);
    QAction *add_folder_action = new QAction(this);
    QAction *remove_selected_action = new QAction(this);
    QAction *remove_all_action = new QAction(this);
    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"));
    //清除原有菜单
    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());
}

二、按钮菜单

使用QPushButton(QToolButton)+QMenu+QAction即可完美实现!

界面拖入一个pushButton按钮;代码实现

   QMenu *remove_menu = new QMenu();
    QAction *remove_selected_action = new QAction(remove_menu);
    QAction *remove_all_action = new QAction(remove_menu);
    remove_menu->addAction(remove_selected_action);
    remove_menu->addAction(remove_all_action);
    ui->pushButton->setMenu(remove_menu);
    ui->pushButton->setText(tr("remove"));
    remove_selected_action->setText(tr("remove selected watermarks"));
    remove_all_action->setText(tr("remove all watermarks"));

三、托盘菜单

托盘菜单实现:通过QSystemTrayIcon+QMenu+QAction实现;

    QSystemTrayIcon *system_tray = new QSystemTrayIcon();
    //放在托盘提示信息、托盘图标
    system_tray ->setToolTip(QString("我就是托盘"));
    system_tray ->setIcon(QIcon(":/sx1.png"));
    //TrayMenu *tray_menu = new TrayMenu();
    QMenu *remove_menu = new QMenu();
    QAction *remove_selected_action = new QAction(remove_menu);
    QAction *remove_all_action = new QAction(remove_menu);
    remove_menu->addAction(remove_selected_action);
    remove_menu->addAction(remove_all_action);
    remove_selected_action->setText(tr("remove selected watermarks"));
    remove_all_action->setText(tr("remove all watermarks"));
    system_tray->setContextMenu(remove_menu);

    //点击托盘执行的事件
    connect(system_tray , SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconIsActived(QSystemTrayIcon::ActivationReason)));
         connect(remove_menu, SIGNAL(showWidget()), this, SLOT(showNormal()));
    //显示托盘
    system_tray->show();
    //托盘显示提示信息
    system_tray->showMessage(QString("托盘标题"), QString("托盘显示内容"));

注:关闭和最小化进入到托盘代码

void Form::closeEvent(QCloseEvent *e)
{
    this->hide();
    e->ignore();
}
void Form::changeEvent(QEvent *e)
{
    if((e->type()==QEvent::WindowStateChange)&&this->isMinimized())
    {
        this->hide();
        e->ignore();
    }
}

 

你可能感兴趣的:(自定义)