Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to emit dataChanged in PyQt5

The code below breaks on self.emit line. It works fine in PyQt4. How to fix this code so it works in PyQt5?

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QObject, pyqtSignal

class ItemDelegate(QtWidgets.QItemDelegate):
    def __init__(self, parent):
        QtWidgets.QItemDelegate.__init__(self, parent)

    def createEditor(self, parent, option, index):
        return QtWidgets.QLineEdit()

    @QtCore.pyqtSlot()
    def setModelData(self, editor, model, index): 
        self.emit(QtCore.SIGNAL("dataChanged(QModelIndex,QModelIndex)"), index, index)  

Edited later:

A working solution:

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QObject, pyqtSignal

class Communicate(QObject):
    data_changed = pyqtSignal(QtCore.QModelIndex, QtCore.QModelIndex)

class ItemDelegate(QtWidgets.QItemDelegate):
    def __init__(self, parent):
        QtWidgets.QItemDelegate.__init__(self, parent)
        self.c = Communicate()

    @QtCore.pyqtSlot()
    def setModelData(self, editor, model, index):
        self.c.data_changed.emit(index, index)
like image 385
alphanumeric Avatar asked Jul 04 '16 04:07

alphanumeric


People also ask

What is emit in pyqt5?

emit can be reimplemented to send specific signal values to the slot function. It is also not yet clear why I would need to send different values from previously existing signal methods. You generally shouldn't be emitting the built in signals. You should only need to emit signals that you define.

What is QtCore pyqt5?

The QtCore module contains the core classes, including the event loop and Qt's signal and slot mechanism. It also includes platform independent abstractions for animations, state machines, threads, mapped files, shared memory, regular expressions, and user and application settings.


2 Answers

As you can read here, QtCore.SIGNAL was discontinued after PyQt4 and is therefore not compatible.

This page explains the new-style signals and slots for PyQt5. The syntax is:

PyQt5.QtCore.pyqtSignal(types[, name[, revision=0[, arguments=[]]]])

Your case could be translated to:

from PyQt5 import pyqtsignal

data_changed = pyqtsignal(QModelindex,QModelIndex)

and to emit your signal:

self.data_changed.emit(index, index)

Edit: Solution adapted from comments below.

like image 89
Ian Avatar answered Oct 04 '22 22:10

Ian


This has become much more simple in PyQt5:

self.dataChanged.emit(index, index, [QtCore.Qt.EditRole])
like image 42
Aaron Digulla Avatar answered Oct 04 '22 22:10

Aaron Digulla