views:

63

answers:

1

hello
i have a QTableView , and i need to show a popup menu that shows the item properties . i need to set the context menu to apear only when you right click over a particular items in that tableview. but coudln't find a way to do it . i can set the context menu to appear when your over the table . i cant have it for each item . so how do i set the context menu over items in the tableview ?


please tell me if the idea was not clear enough
thanks in advance

+2  A: 

Assuming you're in control of when the menu pops up, then you'll want to use the indexAt(QPoint) member function in order to determine what item the mouse is over.

If you're not currently in control of when the menu shows up, you'll need to set the view's contextMenuPolicy to something that will give you control over it.

For example, if you subclass and override contextMenuEvent the implementation might look something like the following:

void MyView::contextMenuEvent ( QContextMenuEvent * event )
{
    QModelIndex index = indexAt(event->pos());
    if (index.data(Qt::UserRole + NEEDS_CONTEXT_MENU_ROLE_OFFSET).toBool())
        // display context menu
    else
        // don't display context menu
}

You could also install an event handler to avoid subclassing.

Kaleb Pederson
thanks for the clarify , but what is (NEEDS_CONTEXT_MENU_ROLE_OFFSET)?what it does and to what class it belongs ?
Moayyad Yaghi
You use `Qt::UserRole + CONSTANT` to represent a custom data role. Thus, it indicates that your model contains data at that specified user role. The constant should denote the purpose. You can put the constant in whatever class you like or namespace you like. Qt uses the `Qt` namespace for such constants.
Kaleb Pederson