0

我有一个 QTreeView 的子类。我需要其中特定项目的自定义上下文菜单。为此,我设置了上下文菜单策略并在 QTreeView 的子类的构造函数中连接了信号“customContextMenuRequested”:

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

我究竟做错了什么?我怎样才能得到我右键单击的项目?

4

2 回答 2

2

如果您contextMenuRequest选择了,TreeItem那么您可以使用它QTreeView::currentIndex()来获取实际选择的QModelIndex.

用于QStandardItemModel::itemFromIndex(const QModelIndex&)获取指向QStandardItem.

以防万一,检查ptr是否为空,你应该很高兴

于 2014-09-27T11:42:32.843 回答
1

您应该将QPoint坐标映射到view->viewport()坐标。

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);
}
于 2014-09-26T08:32:38.243 回答