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 は、QTreeview のこのサブクラスのモデルである QStandardItemModel へのポインターです。

問題は、取得した「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 が null かどうかを確認してください。

于 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 に答える