QT5 QTreeView添加右鍵菜單


C++ QT5學習——QTreeView控件創建右鍵菜單

QTreeView是QWidget的子類,我們再改寫QTreeView類的時候,注意的是繼承關系。

1.TreeView.h

class TreeView : public QTreeView//記得加public 不然是私有繼承
{
    Q_OBJECT //使用信號與槽所必需的
    public:
        TreeView();   
    public slots:
        void slotCustomContextMenu(const QPoint &point);//創建右鍵菜單的槽函數
};

切入正題。

對於QTreeView實現右鍵菜單是通過信號與槽實現的。

我們在點擊右鍵的時候會發生customContextMenuRequested(const QPoint &)信號。我們根據這個信號創建菜單就行了

2.TreeView.cpp

TreeView::TreeView() :QTreeView() //構造函數
{

    this->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(this,SIGNAL(customContextMenuRequested(const QPoint &)),this, SLOT(slotCustomContextMenu(const QPoint &)));
}

void TreeView::slotCustomContextMenu(const QPoint &point) //槽函數定義
{
        QMenu *menu = new QMenu(this);
        QAction *a1=new QAction(tr("上傳"));
        menu->addAction(a1);
        QAction *a2=new QAction(tr("移動"));
        menu->addAction(a2);
        QAction *a3=new QAction(tr("復制"));
        menu->addAction(a3);
        QAction *a4=new QAction(tr("刪除"));
        menu->addAction(a4);
        menu->exec(this->mapToGlobal(point));

}

這樣就實現了右鍵的菜單顯示

3.效果顯示

捕獲.PNG


免責聲明!

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



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