我有一个 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
我究竟做错了什么?我怎样才能得到我右键单击的项目?