質問

I have a Qt combo box. When it pops, items are listed down. When right clicking an item, I hope a context menu to pop up. Any way to implement it? I find a function onContextMenuEvent under QComboBox. Does it help? Thanks.

役に立ちましたか?

解決

You can obtain the list widget using QComboBox::view. You can add a context menu to the list as usual. But also you should install event filter on the view's viewport and block right click events because such events cause popup list to close.

In the initialization:

QAbstractItemView* view = ui->comboBox->view();
view->viewport()->installEventFilter(this);
view->setContextMenuPolicy(Qt::CustomContextMenu);
connect(view, SIGNAL(customContextMenuRequested(QPoint)), 
        this, SLOT(list_context_menu(QPoint)));

Event filter:

bool MainWindow::eventFilter(QObject *o, QEvent *e) {
  if (e->type() == QEvent::MouseButtonRelease) {
    if (static_cast<QMouseEvent*>(e)->button() == Qt::RightButton) {
      return true;
    }
  }
  return false;
}

In the slot:

void MainWindow::list_context_menu(QPoint pos) {
  QAbstractItemView* view = ui->comboBox->view();
  QModelIndex index = view->indexAt(pos);
  if (!index.isValid()) { return; }
  QMenu menu;
  QString item = ui->comboBox->model()->data(index, Qt::DisplayRole).toString();
  menu.addAction(QString("test menu for item: %1").arg(item));
  menu.exec(view->mapToGlobal(pos));
}

In this example items are identified by their displayed texts. But you also can attach additional data to items using QComboBox::setItemData. You can retrieve this data using ui->comboBox->model()->data(...) with the role that was used in setItemData.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top