How to add Action specific index on Qtreeview ?



  • How to add Action specific index on Qtreeview ?


  • Qt Champions 2016

    @takoo
    Hello,
    I don't understand the question, you have to elaborate. What is it you're trying to achieve?

    Kind regards.



  • Hi @kshegunov
    example :
    Apple
    ---a
    ---b

    Pear
    ---c
    ---d

    How to make another context menu for Pear and How to make another context menu for Apple?

    so Apple and Pear context menu will be different.


  • Qt Champions 2016

    @takoo
    Okay. You can intercept the context menu events for the tree view. Are you working with a QTreeView subclass? Let's assume you are; you can override the QWidget::contextMenuEvent handler and process the event yourself. Then from the QContextMenuEvent you can retrieve the position in widget coordinates, and finally you can get the QModelIndex that's corresponding to the item at that poistion through the QAbstractItemView::indexAt method. Here's a bit more information on the subject (it's an example from the docs). Something like this should suffice to get you started:

    class MyTreeView : public QTreeView
    {
        Q_OBJECT
    public:
        // ...
    protected:
        virtual void contextMenuEvent(QContextMenuEvent *) Q_DECL_OVERRIDE;
    };
    
    void MyTreeView::contextMenuEvent(QContextMenuEvent * event)
    {
        QPoint position = event->pos();
        QModelIndex itemIndex = indexAt(position);
    
        // ... Decide based on the model index what context menu you'll be showing ...
    }
    

    Kind regards.



  • Thanks for reply



  • @kshegunov I did not understand anything. Please Can you give me example code (.cpp including)


  • Qt Champions 2016

    @takoo said:

    Please Can you give me example code (.cpp including)

    But I did, I sourced a full example from the Qt documentation with 4 files (at the bottom), the header, the sources and the project file.
    Did you miss the link? Here it is:
    http://doc.qt.io/qt-5/qtwidgets-mainwindows-menus-example.html

    Kind regards.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.