在 TreeView 使用右鍵選單
前言
在之前的 TreeView 的基本應用 裡簡單的操作 TreeView ,但 TreeView 很容易需要可以對選取的節點做操作,這個時候就需要使用到右鍵選單,在此把學習的過程做個紀錄。內容
先到 [ GitLab ] HelloQt 下載範例,這次應用的專案路徑(HelloQt' directory)/TreeView/CustomMenu,執行結果如下
![]() |
| 範例的執行結果 |
範例會產生基本的樹節點,在選取節點並按下右鍵可以跳出選單。
接著來看看程式的操作,先看到 MainWindow::MainWindow() ,程式碼如下
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
, m_pTreeViewCustomMenu( NULL )
{
ui->setupUi(this);
//
QStandardItemModel* pModel = new QStandardItemModel(ui->treeView);
pModel->setHorizontalHeaderLabels( QStringList()<<QStringLiteral("Name")<<QStringLiteral("Comment") );
QStandardItem* pItemRoot1 = new QStandardItem(QStringLiteral("root1") );
//first
pItemRoot1->setChild( 0 ,0 ,new QStandardItem(QStringLiteral("child") ) );
pItemRoot1->setChild( 0 ,1 ,new QStandardItem(QStringLiteral("I'm child") ) );
//
pModel->appendRow( pItemRoot1 );
//
ui->treeView->setModel( pModel );
//
ui->treeView->setContextMenuPolicy( Qt::CustomContextMenu );
//
connect( ui->treeView , &QTreeView::customContextMenuRequested , this , &MainWindow::onTreeViewCustomMenu );
//Set up custom menu
m_pTreeViewCustomMenu = new QMenu( this );
QAction* pAct1 = new QAction( "Action 1" , this );
connect( pAct1 , &QAction::triggered , this , &MainWindow::onTreeViewAction1Trigger );
m_pTreeViewCustomMenu->addAction( pAct1 );
QAction* pAct2 = new QAction( "Action 2" , this );
connect( pAct2 , &QAction::triggered , this , &MainWindow::onTreeViewAction2Trigger );
m_pTreeViewCustomMenu->addAction( pAct2 );
QAction* pAct3 = new QAction( "Action 3" , this );
connect( pAct3 , &QAction::triggered , this , &MainWindow::onTreeViewAction3Trigger );
m_pTreeViewCustomMenu->addAction( pAct3 );
}
先看到初始化的部分,裡面有個成員"m_pTreeViewCustomMenu",這是一個型別為"QMenu"的指標,這個類別其實就是 Qt 用來處理右鍵選單的類別,接著會程式開始製造樹的節點並綁定到 TreeView ,然後這點很重要, TreeView 能否對右鍵有反應是需要經過設定,預設值沒辦法,所以透過"setContextMenuPolicy()"來設定,設為後還要綁定事件,讓它可以在右鍵點選後觸發事件,最後的部分是對"m_pTreeViewCustomMenu"做初始化的動作,用法類似樹的結構,每個節點都是"QAction",範例連續產生 3 個"QAction",並個別對其綁定事件來觸發行為。
接著來看事件的實作,程式碼如下
void MainWindow::onTreeViewCustomMenu( const QPoint& point )
{
//
m_pTreeViewCustomMenu->popup( ui->treeView->viewport()->mapToGlobal( point ) );
}
void MainWindow::onTreeViewAction1Trigger()
{
qDebug( "Action1 triggered" );
}
void MainWindow::onTreeViewAction2Trigger()
{
qDebug( "Action2 triggered" );
}
void MainWindow::onTreeViewAction3Trigger()
{
qDebug( "Action3 triggered" );
}
在"onTreeViewCustomMenu()"裡直接透過"popup()"來顯示選單,事件本身雖然會傳送一個位址過來,但該位址並不能直接用,要經過"mapToGlobal()"轉換才能使用,"QAction"的事件的部分就單純地為個別顯示偵錯訊息,如果需要知道目前選取的節點可以參考 TreeView 的基本應用 裡的按鈕事件。
參考資料
[ doc.qt.io ] QTreeView Class[ doc.qt.io ] QMenu Class
相關文章與資料
[ GitLab ] HelloQtTreeView 的基本應用

沒有留言:
張貼留言