Nuh Yamin
Nuh Yamin

Reputation: 353

How to get the return value of mousePressEvent of other widget in PyQt5

How can I get the value returned from mousePressEvent of a widget and apply it to another widget?

Here's the widget with the mousePressEvent:

class Text(QTextEdit):
    ...

    def mousePressEvent(self, event):
        if event.button()==Qt.LeftButton:        
            return "test"

Now I want to use the string returned from the event and apply it to another widget:

class OtherWidget(QWidget):
    ...
    self.label=QLabel()
    self.label.setText(???) # <=== How to put the string here?
    ...

How can I do that? I have tried the following but it does not work.

    self.label.setText(Text().mousePressEvent())

Upvotes: 1

Views: 3088

Answers (1)

eyllanesc
eyllanesc

Reputation: 243945

The events do not return anything for what you point out is impossible, Qt to send information asynchronously uses the signals, in the next part I show an example:

from PyQt5 import QtCore, QtWidgets

class Text(QtWidgets.QTextEdit):
    mousePressSignal = QtCore.pyqtSignal(str)

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            text = "test: {}-{}".format(event.pos().x(), event.pos().y())
            self.mousePressSignal.emit(text)

class OtherWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(OtherWidget, self).__init__(parent)
        self.label = QtWidgets.QLabel()
        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.label, alignment=QtCore.Qt.AlignCenter)

    @QtCore.pyqtSlot(str)
    def setText(self, text):
        self.label.setText(text)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    t = Text()
    o = OtherWidget()
    o.resize(640, 480)
    t.mousePressSignal.connect(o.setText)
    t.show()
    o.show()
    sys.exit(app.exec_())

Upvotes: 3

Related Questions