Reputation: 121
Hi I'm working on a project in Python 3.5 and Pyqt5, I want to add a right click on a treeWidget Item so I can create a contextual menu with actions, but I didn't find that in PyQt5.
Upvotes: 3
Views: 7896
Reputation: 303
To post an updated answer. This is what worked for me:
class MainWindow_W():
def __init__(self):
self.app = QtWidgets.QApplication(sys.argv)
self.MainWindow = QtWidgets.QMainWindow()
self.ui = Ui_MainWindow()
self.ui.setupUi(self.MainWindow)
# Connect the contextmenu
self.ui.treeWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.ui.treeWidget.customContextMenuRequested.connect(self.menuContextTree)
def menuContextTree(self, point):
# Infos about the node selected.
index = self.ui.treeWidget.indexAt(point)
if not index.isValid():
return
item = self.ui.treeWidget.itemAt(point)
name = item.text(0) # The text of the node.
# We build the menu.
menu = QtWidgets.QMenu()
action = menu.addAction("Souris au-dessus de")
action = menu.addAction(name)
menu.addSeparator()
action_1 = menu.addAction("Choix 1")
action_2 = menu.addAction("Choix 2")
action_3 = menu.addAction("Choix 3")
menu.exec_(self.ui.treeWidget.mapToGlobal(point))
Upvotes: 3
Reputation: 121
Problem Solved actually, so this is how you add a right click contextual menu in a QtreeWidget Area
def menuContextuelAlbum(self, event):
self.menu_contextuelAlb = QtWidgets.QMenu(self.treeWidget)
ajoutFileAtt = self.menu_contextuelAlb.addAction("Ajouter l'album à la file d'attente")
action2 = self.menu_contextuelAlb.exec_(self.treeWidget.mapToGlobal(event))
if action2 is not None:
if action2 == ajoutFileAtt:
self.addAlbumlistAtt()
and launch it with:
self.treeWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.treeWidget.customContextMenuRequested.connect(self.menuContextuelAlbum)
self.actionOuvrir.triggered.connect(self.menu)
Upvotes: 4
Reputation: 2005
You need to create your own QTreeWidget
with your own mousePressEvent
.
in your mousePressEvent
check if the event type is a right click and if it is, do whatever you want. Then, when you add widgets in your tree, make sure it will be your class which is added and not a QTreeWidget
.
So something like that:
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import QTreeWidgetItem
import sys
class MyTreeWidget(QtGui.QTreeWidget):
def __init__(self, parent = None):
QtGui.QTreeWidget.__init__(self, parent)
def mousePressEvent (self, event):
print("child clicked ! ")
if event.button() == QtCore.Qt.RightButton:
print("right click !")
QtGui.QTreeWidget.mousePressEvent(self, event)
def main():
app = QtGui.QApplication(sys.argv)
QtGui.qApp = app
pointListBox = MyTreeWidget()
root = QTreeWidgetItem(pointListBox, ["root"])
A = QTreeWidgetItem(root, ["A"])
barA = QTreeWidgetItem(A, ["bar", "i", "ii"])
bazA = QTreeWidgetItem(A, ["baz", "a", "b"])
pointListBox.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Upvotes: 2