I have implemented contextual menus in QTreeView items with the following code
MyDerivedQTreeView->setModel(MyDerivedQAbstractItemModel);
MyDerivedQTreeView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(MyDerivedQTreeView,
SIGNAL(customContextMenuRequested(const QPoint &)),
MyDerivedQAbstractItemModel(),
SLOT(contextualMenu(const QPoint &)));
void MyDerivedQAbstractItemModel::contextualMenu(const QPoint& point)
{
QMenu *menu = new QMenu;
menu->addAction(QString("Test Item"), this, SLOT(test_slot()));
menu->exec(MyDerivedQTreeView->mapToGlobal(point));
}
MyDerivedQAbstractItemModel::contextualMenu() gets called and I can see the contextual menu.
Problem is contextual menu should be visible only if user right-clicks on an item and it should be customized as per the item selected.
How do I get whether/which item is selected from QPoint information? I am on Qt 4.5.3.
Maybe you could use the indexAt() method of QTreeView to get the item where the click is made, before constructing your custom menu.
Maybe this code will help you:
==> dialog.h <==
QStandardItemModel *model;
QSortFilterProxyModel *proxyModel;
QTreeView *treeView;
==> dialog.cpp <==
void CImportTabWidget::createGUI() {
...
proxyModel = new QSortFilterProxyModel;
proxyModel->setDynamicSortFilter(true);
treeView = new QTreeView;
treeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
treeView->setRootIsDecorated(false);
treeView->setAlternatingRowColors(true);
treeView->setModel(proxyModel);
model = new QStandardItemModel(0, 4);
model->setHeaderData(0, Qt::Horizontal, tr("Name"));
model->setHeaderData(1, Qt::Horizontal, tr("Comment"));
model->setHeaderData(2, Qt::Horizontal, tr("Size"));
model->setHeaderData(3, Qt::Horizontal, tr("Date"));
fillTreeViewData();
proxyModel->setSourceModel(model);
...
}
//////////////////////////////////////////////////////////////////////////
void CImportTabWidget::createMenus() {
treeView->setContextMenuPolicy(Qt::CustomContextMenu);
connect(treeView,
SIGNAL(customContextMenuRequested(const QPoint &)),
this,
SLOT(contextMenu(const QPoint &)));
}
//////////////////////////////////////////////////////////////////////////
void CImportTabWidget::contextMenu(const QPoint &widgetXY) {
Q_UNUSED(widgetXY);
QMenu menu(this);
/* Условия для меню */
deleteAct->setEnabled((!model->rowCount()) ? false : true );
deleteAllAct->setEnabled((!model->rowCount()) ? false : true );
/* Находим индекс */
QModelIndex index = treeView->currentIndex();
QString fileName = model->data(model->index(index.row(), 0)).toString();
if (!fileName.isEmpty()) {
importAct->setText(tr("Import %1").arg(fileName));
//deleteAct->setText(tr("Delete %1").arg(fileName));
}
/* Формируем меню */
menu.addAction(deleteAct);
menu.addAction(deleteAllAct);
menu.exec(QCursor::pos());
}
Good luck!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With