If I want a context menu on a view, then I usually do something like this (assuming I'm not subclassing the view itself):
listView->installEventFilter(this);
if(obj
== listView
&& e
->type
== QEvent::ContextMenu) { showViewContextMenu(static_cast<QContextMenuEvent*>(e)->pos());
}
return ...;
}
listView->installEventFilter(this);
bool Window::eventFilter(QObject *obj, QEvent *e) {
if(obj == listView && e->type == QEvent::ContextMenu) {
showViewContextMenu(static_cast<QContextMenuEvent*>(e)->pos());
}
return ...;
}
To copy to clipboard, switch view to plain text mode
... or ...
listView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(listView,
SIGNAL(customContextMenuRequested
(QPoint)),
this,
SLOT(showViewContextMenu
(QPoint)));
listView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(listView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showViewContextMenu(QPoint)));
To copy to clipboard, switch view to plain text mode
... and then ...
void Window
::showViewContextMenu(const QPoint &pt
) { modelIndexForContextMenu = idx; // optional, to let slots know what index is the base for the context menu
fillMenuWithActionsDependingOnIndex(&menu, idx);
menu.exec(listView->viewport()->mapToGlobal(pt));
}
void Window::showViewContextMenu(const QPoint &pt) {
QModelIndex idx = listView->indexAt(pt);
modelIndexForContextMenu = idx; // optional, to let slots know what index is the base for the context menu
QMenu menu;
fillMenuWithActionsDependingOnIndex(&menu, idx);
menu.exec(listView->viewport()->mapToGlobal(pt));
}
To copy to clipboard, switch view to plain text mode
assuming I have a bunch of QAction objects with triggered() signals already connected to respective slots I can do:
void Window
::fillMenuWithActionsDependingOnIndex(QMenu *menu,
const QModelIndex &idx
) { ui->action1->setEnabled(idx.parent().isValid());
ui->action2->setEnabled(idx.column() == 0);
// etc.
menu->addAction(ui->action1);
menu->addAction(ui->action2);
// etc.
}
void Window::fillMenuWithActionsDependingOnIndex(QMenu *menu, const QModelIndex &idx) {
ui->action1->setEnabled(idx.parent().isValid());
ui->action2->setEnabled(idx.column() == 0);
// etc.
menu->addAction(ui->action1);
menu->addAction(ui->action2);
// etc.
}
To copy to clipboard, switch view to plain text mode
Everything else works on its own.
Of course that's only one of possible approaches.
By the way, code in the article you linked to is flawed and can cause an application to crash. By some luck it probably doesn't crash but it doesn't make the code valid.
Bookmarks