2

Im trying to add right-click functionality to items in a list widget in PyQt4 using Python. Id like a pop up context menu to show that has buttons and when clicked should perform some function.

How do I get a context menu to pop up when right clicking on each of the items?

0

1 Answer 1

11

I have come up with a pretty simple way of doing this and works perfectly. In the ControlMainWindow class add the following to initialise the Context menu policy as CustomeContextMenu where listWidget_extractedmeters will be the name of your QListWidget:

    self.listWidget_extractedmeters.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.listWidget_extractedmeters.connect(self.listWidget_extractedmeters,QtCore.SIGNAL("customContextMenuRequested(QPoint)" ), self.listItemRightClicked)

Then in the ControlMainwindow class the following functions allow you to add context menu items and to call a funtion that performs some functionality:

def listItemRightClicked(self, QPos): 
    self.listMenu= QtGui.QMenu()
    menu_item = self.listMenu.addAction("Remove Item")
    self.connect(menu_item, QtCore.SIGNAL("triggered()"), self.menuItemClicked) 
    parentPosition = self.listWidget_extractedmeters.mapToGlobal(QtCore.QPoint(0, 0))        
    self.listMenu.move(parentPosition + QPos)
    self.listMenu.show() 

def menuItemClicked(self):
    currentItemName=str(self.listWidget_extractedmeters.currentItem().text() )
    print(currentItemName)
Sign up to request clarification or add additional context in comments.

1 Comment

I'd like to add that this is also possible with QtDesigner. You can set the CustomContextMenu policy for the QListWidget and then connect the customContextMenuRequested(QPoint) signal to whatever slot you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.