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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM