Context menu on tree view
-
How about:
@
void MainWindow::contextualMenu(const QPoint& point)
{
QModelIndex index = view->currentIndex();if(view->rootIndex() == index)
{
QMenu *menu = new QMenu(view);
QString fileName = model->data(model->index(index.row(), 0),0).toString();
menu->addAction(QString("Import"), this, SLOT(test_slot()));
menu->addAction(QString("Export"), this, SLOT(test_slot()));
menu->exec(QCursor::pos());
}
}
@ -
If by Root Node you mean an item that has children you should instead check for that condition.
@
if(model->hasChildren(index))
{}
@To set the root index use the "setRootIndex method":https://qt-project.org/doc/qt-4.8/qabstractitemview.html#setRootIndex . But there's only one root item in a view.
-
-
I think you want to have a behaviour like this:
@
void MainWindow::contextualMenu(const QPoint& point)
{
QModelIndex index = view->currentIndex();if(view->model()->hasChildren(index)) { QMenu *menu = new QMenu(view); QString fileName = model->data(model->index(index.row(), 0),0).toString(); menu->addAction(QString("Import"), this, SLOT(test_slot())); menu->addAction(QString("Export"), this, SLOT(test_slot())); menu->exec(QCursor::pos()); }
}
@ -
Well then you have to check for the two different cases and create the menu depending on the result of the check.
@
void MainWindow::contextualMenu(const QPoint& point)
{
QModelIndex index = view->currentIndex();if(view->rootIndex() == index /*check if index is that of the RootNode item*/) { // construct the context menu required for ChildItem items } else { if(view->model()->hasChildren(index) /*check if the index is that of a ChildItem item*/) { // construct the context menu required for the RootNode item } } }
@
-
[quote author="Rajveer" date="1337681154"]Hi
In my case if i right click on root node it will not enter the below if condition
@
QModelIndex index = view->currentIndex();
if(view->rootIndex() == index)
{
}
@And how to check for child nodes?[/quote]
Well if you haven't set a root node, then of course the check performed by the first if condition will return false. And if you care to read my last post you will see that I already told you how to check for child nodes.
You might want to put some effort into this yourself.