Andrew Ring
Andrew Ring

Reputation: 3343

PyQt Table Header Context Menu

I am working on a QTableView displaying a custom model subclasses from QAbstractTableModel in PyQt4. I need to be able to allow the user to set which column they want to serve as a specific type of data. To achieve this I want to implement a context menu when clicking on the header of a column, allowing options to set it as these types. I'm not sure how to create a context menu like this which can differentiate between different columns. Can anyone point me in the right direction?

Thanks

Upvotes: 0

Views: 2918

Answers (1)

Eric Hulser
Eric Hulser

Reputation: 4022

You can access the information from the header view. You can do something like:

def __init__( self, parent ):
    # initialize class
    ...

    # setup menu options
    header = self.ui.tree.header()
    header.setContextMenuPolicy(Qt.CustomContextMenu)
    header.customContextMenuRequested.connect( self.showHeaderMenu )

def showHeaderMenu( self, point ):
    column = self.ui.tree.header().logicalIndexAt(point.x())

    # show menu about the column
    menu = QMenu(self)
    menu.addAction('Hide Column')

    menu.popup(header.mapToGlobal(pos))

Upvotes: 3

Related Questions