2014-09-26 457 views
0

我有一個QTreeView的子類。我需要爲其中的特定項目定製上下文菜單。爲了得到這個我設置的上下文菜單政策和QTreeView則子類的構造函數連接信號「customContextMenuRequested」:現在獲取QStandardItem的QTreeView的自定義上下文菜單

setContextMenuPolicy(Qt::CustomContextMenu); 

QObject::connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(onCustomContextMenu(const QPoint &))); 

,在槽函數「onCustomContextMenu」我得到的上下文菜單創作中的地位作爲QPoint。我想獲得此位置顯示的QStandardItem。我嘗試這樣做:

void t_my_tree_view::onCustomContextMenu(const QPoint &point) 
{ 
    QModelIndex index = this->indexAt(point); 
    QStandardItem* item_ptr = m_item_model->item(index.row, index.column()); 
} 

m_item_model是一個指向QStandardItemModel是在這個子類QTreeView則模型。

問題是,我得到的「item_ptr」有時是錯的,或者它是NULL。如果我的模型看起來像這樣這將是NULL:

invisibleRootItem
| -item_on_level_1
| -item_on_level_2
| -item_on_level_2
| -item_on_level_2 < - 這是正確的點擊是
項目| -item_on_level_2

我在做什麼錯?我怎樣才能得到我右鍵點擊的項目?

回答

0

您應該將地圖QPoint座標設置爲view->viewport()座標。

Prefferable方式是實現自定義QStyledItemDelegate與壓倒一切的editorEvent,如:

bool LogDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, QStyleOptionViewItem const& option, QModelIndex const& index) 
{ 
    switch (event->type()) 
    { 
    case QEvent::MouseButtonRelease: 
     { 
      QMouseEvent* me = static_cast<QMouseEvent *>(event); 
      if (me->button() == Qt::RightButton) 
      { 
       QMenu menu; 
       QAction* copy = new QAction("Copy", this); 
       connect(copy, SIGNAL(triggered()), SIGNAL(copyRequest())); 
       menu.addAction(copy); 
       menu.exec(QCursor::pos()); 
       copy->deleteLater(); 
      } 
     } 
     break; 

    default: 
     break; 
    } 

    return QStyledItemDelegate::editorEvent(event, model, option, index); 
} 
1

如果您contextMenuRequest選擇TreeItem那麼你可以使用QTreeView::currentIndex()獲得選擇QModelIndex實際。

使用QStandardItemModel::itemFromIndex(const QModelIndex&)可獲得指向QStandardItem的指針。

爲防萬一,請檢查ptr是否爲空,並且您應該好轉