QT 鼠標右鍵菜單

QWidget及其子類都可有右鍵菜單,因爲QWidget有以下兩個與右鍵菜單有關的函數:

Qt::ContextMenuPolicy contextMenuPolicy () const

void setContextMenuPolicy ( Qt::ContextMenuPolicy policy )

Qt::ContextMenuPolicy枚舉類型包括:Qt::DefaultContextMenu, Qt::NoContextMenu, Qt::PreventContextMenu, Qt::ActionsContextMenu, and Qt::CustomContextMenu。

使用方式如下:


1)默認是Qt::DefaultContextMenu。
它是利用右鍵菜單事件contextMenuEvent()來處理(which means the contextMenuEvent() handler is called)。就是要重寫contextMenuEvent( QContextMenuEvent * event )函數。

實例:

void CGuiMainwindow::contextMenuEvent(QContextMenuEvent* e)
{
QMenu *menu = new QMenu();
menu->addSeparator();
menu->addSeparator();
menu->addAction(Act_Maxsize);
menu->addSeparator();
menu->addSeparator();
menu->addAction(Act_Normal);
menu->addSeparator();
menu->addSeparator();
menu->exec(e->globalPos());
delete menu;
}

注意,裏面的action是需要自己實現編輯好的,可以在action editor內先進行編輯。


2)使用Qt::CustomContextMenu。
它是發出QWidget::customContextMenuRequested信號,注意僅僅只是發信號,意味着要自己寫顯示右鍵菜單的slot。
這個信號是QWidget唯一與右鍵菜單有關的信號(也是自有的唯一信號),同時也是很容易被忽略的signal:

void customContextMenuRequested ( const QPoint & pos )

該信號的發出條件是:用戶請求contextMenu(常規就是鼠標右擊啦)且同時被擊的widget其contextMenuPolicy又是Qt::CustomContextMenu。
注意:pos是該widget接收右鍵菜單事件的位置,一般是在該部件的座標系中。但是對於QAbstratScrollArea及其子類例外,是對應着其視口viewport()的座標系。如常用的QTableView、QHeaderView就是QAbstratScrollArea的子類。
因爲僅發信號,所以需自己寫顯示右鍵菜單的slot來響應,例如一個表格(QTableView類型)表頭的顯示右鍵菜單槽:
datatable->horizontalHeader()->setContextMenuPolicy(Qt::CustomContextMenu);
connect(datatable->horizontalHeader(), SIGNAL(customContextMenuRequested(const QPoint&)), 

        this, SLOT(show_contextmenu(const QPoint&)));//this是datatable所在窗口
QMenu *cmenu = NULL;
show_contextmenu(const QPoint& pos)
{
    if(cmenu)//保證同時只存在一個menu,及時釋放內存
    {
        delete cmenu;
        cmenu = NULL;
    }
    QMenu cmenu = new QMenu(datatable->horizontalHeader());
    
    QAction *ascendSortAction = cmenu->addAction("升序");
    QAction *descendSortAction = cmenu->addAction("降序");
    QAction *filterAction = cmenu->addAction("過濾");
    QAction *reshowAction = cmenu->addAction("重載");
    
    connect(ascendSortAction, SIGNAL(triggered(bool)), this, SLOT(sort_ascend()));
    connect(descendSortAction, SIGNAL(triggered(bool)), this, SLOT(sort_descend()));
    connect(filterAction, SIGNAL(triggered(bool)), this, SLOT(show_filter_dlg()));
    connect(reshowAction, SIGNAL(triggered(bool)), this, SLOT(reshow_data()));
    
    cmenu->exec(QCursor::pos());//在當前鼠標位置顯示
    //cmenu->exec(pos)是在viewport顯示
}

也可先做好cmenu,好處是始終使用一個:
    QMenu cmenu = new QMenu(datatable->horizontalHeader());
    
    QAction *ascendSortAction = cmenu->addAction("升序");
    QAction *descendSortAction = cmenu->addAction("降序");
    QAction *filterAction = cmenu->addAction("過濾");
    QAction *reshowAction = cmenu->addAction("重載");
    
    connect(ascendSortAction, SIGNAL(triggered(bool)), this, SLOT(sort_ascend()));
    connect(descendSortAction, SIGNAL(triggered(bool)), this, SLOT(sort_descend()));
    connect(filterAction, SIGNAL(triggered(bool)), this, SLOT(show_filter_dlg()));
    connect(reshowAction, SIGNAL(triggered(bool)), this, SLOT(reshow_data()));
show_contextmenu(const QPoint& pos)
{
    if(cmenu)
    {
        cmenu->exec(QCursor::pos());
    }
}


3)使用Qt::ActionsContextMenu。
把部件的所有action即QWidget::actions()作爲context menu顯示出來。
還是上面的例子,要在表格(QTableView類型)表頭顯示右鍵菜單:
        QAction *ascendSortAction = new QAction("升序", this);
        QAction *descendSortAction = new QAction("降序", this);
        QAction *filterAction = new QAction("過濾", this);
        QAction *unfilterAction = new QAction("取消過濾", this);
    
        connect(ascendSortAction, SIGNAL(triggered(bool)), this, SLOT(sort_ascend()));
        connect(descendSortAction, SIGNAL(triggered(bool)), this, SLOT(sort_descend()));
        connect(filterAction, SIGNAL(triggered(bool)), this, SLOT(filter_table()));
        connect(unfilterAction, SIGNAL(triggered(bool)), this, SLOT(unfilter_table()));
    
        datatable->horizontalHeader()->addAction(ascendSortAction);
        datatable->horizontalHeader()->addAction(descendSortAction);
        datatable->horizontalHeader()->addAction(filterAction);
        datatable->horizontalHeader()->addAction(unfilterAction);
         
        datatable->horizontalHeader()->setContextMenuPolicy(Qt::ActionsContextMenu);

另外兩個就是不顯示context menu了:
Qt::NoContextMenu
    the widget does not feature a context menu, context menu handling is deferred to the widget's parent.
    
Qt::PreventContextMenu
    the widget does not feature a context menu, and in contrast to NoContextMenu, the handling is not deferred to the widget's parent. This means that all right mouse button events are guaranteed to be delivered to the widget itself through mousePressEvent(), and mouseReleaseEvent().

補充:
    使用Qt::ActionsContextMenu比較簡潔,但是如果需要根據當前菜單彈出的位置來定義不同菜單,或者像上個例子,在表格(QTableView類型)表頭顯示右鍵菜單時,我需要知道是哪一列表頭被點擊,從而在後來調用sort_ascend()排序函數時能夠根據不同列進行不同排序策略,那麼Qt::ActionsContextMenu就做不到了。
    這種需要捕捉彈出位置的情況只好用Qt::ActionsContextMenu了,customContextMenuRequested ( const QPoint & pos )信號返回點擊位置pos(在表頭視口座標系中位置),然後表頭即可調用logicalIndexAt(pos)函數得到被點擊section對應的index即被點擊部分的列號,然後存下來可供後面action激活的排序槽使用。
show_contextmenu(const QPoint& pos)
{
    //get related column of headerview
    contextmenu_column = datatable->horizontalHeader()->logicalIndexAt(pos);

    //show contextmenu
    if(cmenu)
    {
        cmenu->exec(QCursor::pos());
    }
}



4)二級菜單實例

準備工作一:定義和實現需要的action,可以用代碼編寫,也可以用creator進行製作。代碼編寫如下

頭文件定義:

QMenu              *popupMenu;                      /*popupMenu*/  //主菜單
    QMenu              *twoPictures;                    /*two pictures*/  // 二級菜單
    QMenu              *onePictures;                    /*one pictures*/ // 二級菜單
    QAction            *firstChannel;                   /*channel 1*/
    QAction            *secondChannel;                  /*channel 2*/
    QAction            *thirdChannel;                   /*channel 3*/
    QAction            *forthChannel;                   /*channel 4*/
    QAction            *frontSection;
    QAction            *backSection;
    QActionGroup       *channels;     //用來實現子菜單選項互斥
    QActionGroup       *sections;

       cpp文件實現:

void layout3::createActions(void)
{
    firstChannel = new QAction(tr("first channel"), this);  //創建新的菜單項
    firstChannel->setCheckable(true);                            //屬性是可選的
    connect(firstChannel, SIGNAL(triggered()), this, SLOT(firstChannelSlot()));       //該菜單項的連接信號和槽

    secondChannel = new QAction(tr("second channel"), this);
    secondChannel->setCheckable(true);
    connect(secondChannel, SIGNAL(triggered()), this, SLOT(secondChannelSlot()));

    thirdChannel = new QAction(tr("third channel"), this);
    thirdChannel->setCheckable(true);
    connect(thirdChannel, SIGNAL(triggered()), this, SLOT(thirdChannelSlot()));

    forthChannel = new QAction(tr("forth channel"), this);
    forthChannel->setCheckable(true);
    connect(forthChannel, SIGNAL(triggered()), this, SLOT(forthChannelSlot()));

    frontSection = new QAction(tr("front section"), this);
    frontSection->setCheckable(true);
    connect(frontSection, SIGNAL(triggered()), this, SLOT(frontSectionSlot()));

    backSection = new QAction(tr("back section"), this);
    backSection->setCheckable(true);
    connect(backSection, SIGNAL(triggered()), this, SLOT(backSectionSlot()));

    channels = new QActionGroup(this);        //創建菜單項組,裏面的菜單項爲互斥
    channels->addAction(firstChannel);         //添加菜單項到組裏
    channels->addAction(secondChannel);
    channels->addAction(thirdChannel);
    channels->addAction(forthChannel);
    firstChannel->setChecked(true);          //設置默認的菜單組的菜單項狀態,firstChannel被選中

    sections = new QActionGroup(this);   //同上
    sections->addAction(frontSection);
    sections->addAction(backSection);
    frontSection->setChecked(true);

}

      準備工作二:編寫相應的action對應的槽函數

/*
 * 槽函數準備爲
 */
void layout3::firstChannelSlot(void)
{
}

void layout3::secondChannelSlot(void)
{
}

void layout3::thirdChannelSlot(void)
{
}

void layout3::forthChannelSlot(void){
}

void layout3::frontSectionSlot(void)
{}

void layout3::backSectionSlot(void)
{}
 最後進行菜單的編輯,重寫void contextMenuEvent ( QContextMenuEvent *event);

void layout3::contextMenuEvent(QContextMenuEvent* e)
{

    popupMenu = new QMenu();  //創建主菜單

    onePictures = popupMenu->addMenu("one pictures");   //在主菜單中創建子菜單one pictures
    onePictures->addAction(firstChannel);               //把action項放入子菜單中
    onePictures->addAction(secondChannel);
    onePictures->addAction(thirdChannel);
    onePictures->addAction(forthChannel);

    popupMenu->addSeparator();
    popupMenu->addSeparator();

    twoPictures = popupMenu->addMenu("two pictures");  //在主菜單中創建子菜單two pictures
    twoPictures->addAction(frontSection);
    twoPictures->addAction(backSection);

    popupMenu->addSeparator();
    popupMenu->addSeparator();

    popupMenu->addAction(ui->actionAbout);              //把action項放入主菜單中
    popupMenu->addSeparator();
    popupMenu->addSeparator();
    popupMenu->addAction(ui->actionBuild);
    popupMenu->addSeparator();
    popupMenu->addSeparator();

    popupMenu->exec(e->globalPos());                    //選擇菜單彈出的位置
    delete popupMenu;
    popupMenu = NULL;

}


結果如下:



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章