在Qt中为QTableView创建弹出菜单,可以通过以下步骤实现:
table_view->installEventFilter(this);
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if (obj == table_view && event->type() == QEvent::MouseButtonPress) {
QMouseEvent *mouse_event = static_cast<QMouseEvent*>(event);
if (mouse_event->button() == Qt::RightButton) {
QPoint global_pos = mouse_event->globalPos();
QPoint table_view_pos = table_view->mapToGlobal(QPoint(0, 0));
QPoint pos = global_pos - table_view_pos;
QModelIndex index = table_view->indexAt(pos);
if (index.isValid()) {
QMenu menu(this);
QAction *action1 = new QAction("Action 1", this);
QAction *action2 = new QAction("Action 2", this);
menu.addAction(action1);
menu.addAction(action2);
menu.exec(global_pos);
}
}
}
return QMainWindow::eventFilter(obj, event);
}
QStandardItemModel *model = new QStandardItemModel(this);
model->setHorizontalHeaderLabels(QStringList() << "Column 1" << "Column 2");
table_view->setModel(model);
这样,在Qt中为QTableView创建弹出菜单的功能就实现了。
领取专属 10元无门槛券
手把手带您无忧上云