user2259784
user2259784

Reputation: 349

How to override event (dropEvent) of a widget in dynamic UI of PyQt?

What am I doing/ What I have so far :

I am using Qt-designer to create PyQt .ui file which I am loading in my python script using QUiLoader which gives me access to the widgets/components as :

self.ui.tree_widget_of_items ( which is a QTreeWidget created in Qt-designer)

I am able to read and write the values of widgets and I am able to use the signal on TreeWidget like this :

self.ui.tree_widget_of_items.itemSelectionChanged.connect(self.myFunction)

What I am trying to do ?

What I have tried but didn't work :

self.ui.tree_widget_of_items.dropEvent = self.drop_action

def drop_action(self,e):
    print "drop action"

I have tried assigning a my own function to dropEvent of TreeWidget but it doesn't get triggered when I drop an item on TreeWidget.

I have also tried :

self.ui.tree_widget_of_items.dragEnterEvent = self.drop_action

I made sure that Drag and Drop is enabled on TreeWidget.

Upvotes: 2

Views: 5130

Answers (2)

Fabio
Fabio

Reputation: 2602

You have to install an event filter on the tree and implement the QObject.eventFilter method in your class.

Example (install event filter):

self.ui.tree_widget_of_items.installEventFilter(self)

And implement eventFilter:

def eventFilter(self, o, e):
    if e.type() == QEvent.DragEnter: #remember to accept the enter event
        e.acceptProposedAction()
        return True
    if e.type() == QEvent.Drop:
        # handle the event
        # ...
        return True
    return False #remember to return false for other event types

See QObject.installEventFilter and QObject.eventFilter

Upvotes: 2

user2259784
user2259784

Reputation: 349

To implement Events in dynamic UI (which means UI created in Qt-designer and used in python tool using .ui file). You need following things :

  1. MainWindow class of your tool should inherit QtGui.QMainWindow

    class main_window(QtGui.QMainWindow):
    
  2. It should call super().init()

    class main_window(QtGui.QMainWindow):
        def __init__(self, parent=None):
            super(main_window, self).__init__(parent)
    
            loader = QUiLoader()
            file = QtCore.QFile(os.path.join(SCRIPT_DIRECTORY, 'mainwindow.ui'))
            file.open(QtCore.QFile.ReadOnly)
            if parent:
                self.ui = loader.load(file, parentWidget=parent)
            else:
                self.ui = loader.load(file)
            file.close()
    
  3. Install EventFilter on component :

    self.ui.tree_widget_of_items.installEventFilter(self)      
    # not --> self.ui.tree_widget_of_items.installEventFilter(self.ui)
    
  4. Define eventFilter() :

    def eventFilter(self, o, e):
    if (o.objectName() == "tree_widget_of_items"):
        if e.type() == QtCore.QEvent.Type.Enter:
            self.drop_action(e)
    

Upvotes: 4

Related Questions