How to implement an interactive QAction with Pyside ? (i.e. How to catch event in a QAction ?)

452 Views Asked by At

It might be a very simple question but I can't figure out how to do it.

The context: I am making an application that can draw polygons in a QGraphicsScene. I would like to implement interactive actions. For example, the user clicks on a button, then clicks on the scene to draw temporary lines, finally the app cuts the polygon with the line.

What I try to achieve

What I try to achieve

What I did Since I didn't find anything here or in the doc, I looked in the LibreCad repository to know how they do it.

https://github.com/LibreCAD/LibreCAD/blob/768285653c46e734a75460928142cda1a33c2c53/librecad/src/lib/actions/rs_actioninterface.h

Their base class inherits from QObject to handle events. It seems that they don't inherit from QAction despite line 40 where one can read "class QAction;". My C++ skills end here. In an act of faith, I wrote the following minimal non-working example in python with PySide.

#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from PySide2.QtCore import QObject
from PySide2.QtWidgets import (QApplication, QMainWindow, QWidget,
                               QGraphicsView, QGraphicsScene,
                               QToolBar, QAction)

class Action(QAction, QObject):
    def __init__(self, name, parent=None):
        super().__init__(name, parent)
        # I also tried to add this, obviously I don't know what I am doing
        #QObject.__init__(parent) 
        
    def keyPressEvent(self, event):
        print("Event handled")
        super().keyPressEvent(event)


class MainWindow(QMainWindow,):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.centralwidget = QWidget()
        self.graphicsView = QGraphicsView(self.centralwidget)
        self.setCentralWidget(self.centralwidget)
        self.scene = QGraphicsScene(0,0,1000,1000)
        self.graphicsView.setScene(self.scene)
        
        toolbar = QToolBar("My toolbar")
        self.addToolBar(toolbar)
        
        knifeActionButton = Action("Knife", self)
        knifeActionButton.setShortcut("K")
        knifeActionButton.triggered.connect(self.cutPolygon)
        toolbar.addAction(knifeActionButton)
    
    def cutPolygon(self):
        print("Action triggered")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    app.exec_()

The question: How to handle events in a QAction to make it interactive?

Please excuse my English, I am a non-native speaker

0

There are 0 best solutions below