2014-09-26 121 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是否为空,并且您应该好转