【问题标题】:Get QStandardItem for the custom context menu of a QTreeView为 QTreeView 的自定义上下文菜单获取 QStandardItem
【发布时间】:2014-09-27 19:42:32
【问题描述】:

我有一个 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

我做错了什么?如何获得我右键单击的项目?

【问题讨论】:

    标签: qt qt5 qtreeview qstandarditemmodel qt5.3


    【解决方案1】:

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

    使用QStandardItemModel::itemFromIndex(const QModelIndex&) 获取指向QStandardItem 的指针。

    以防万一,检查 ptr 是否为空,你应该好好去

    【讨论】:

      【解决方案2】:

      您应该将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);
      }
      

      【讨论】:

        猜你喜欢
        • 2016-06-06
        • 2015-11-10
        • 1970-01-01
        • 1970-01-01
        • 2021-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多