contextmenu in QTableView

Continue with my last post about QtableView tutorial (fill Qtableview with value), I try to create another post about how to create contextmenu in QtableView. With this tutorial, you can implementated contextmenu in other Widget in Qt like QtableWidget, QlistWidget and other. The basic idea how to create contextmenu in QtableView is like with contextmenu in QtableWidget, contextmenu in Qlistwidget and other.

We can add contextmenu in widget with change setContextMenuPolicy property with value Qt::CustomContextMenu. We can set contextmenu in QtableView with command :

tblv->setContextMenuPolicy(Qt::CustomContextMenu);
connect(tblv, SIGNAL(customContextMenuRequested( const QPoint& )),
this, SLOT(tablev_customContextMenu( const QPoint& )));

If we want to add contextmenu in QtableView header, we must get object from QtableView header and set contextmenu in that object. This is sample command how to implementated this :

//connect horizontal header QTableView with contextmenu
horizontalHeader = tblv->horizontalHeader();
horizontalHeader->setContextMenuPolicy(Qt::CustomContextMenu);
connect(horizontalHeader, SIGNAL(customContextMenuRequested( const QPoint& )),
this, SLOT(tablev_customContextMenu( const QPoint& )));

This is output from QTableView tutorial  create contextmenu in QtableView and contexmenu in QtableView Header :

You can download my full source code  (create contextmenu in QtableView) from here.

2 Comments

Add a Comment

Your email address will not be published. Required fields are marked *