Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine who emitted the signal?

Tags:

python

pyqt

I develop an application on PyQt, I like the signal-slot model, but is there any way to determine the emitter of signal? I hope that there is a way, because it will let to write more generic code without defining lots of slots for each similar signal.

like image 693
kravitz Avatar asked Jan 10 '11 00:01

kravitz


2 Answers

I think that I opened a question too early, because I found an answer on google by myself. When slot is activated by emitter, the pointer of emitter stored, and can be retrieved by

QObject::sender()

and as a result can be accessed in PyQt by:

@QtCore.pyqtSlot()
def someSlot(self):
    self.sender()
like image 143
kravitz Avatar answered Oct 28 '22 21:10

kravitz


You might want to look into the QSignalMapper class, as it provides a means to associate either an int, string, or widget paramters to an object that sends a given signal. The main limitation is that the signal/slot being mapped needs to be parameter-less.

C++ example from the QT4.7 documentation:

 ButtonWidget::ButtonWidget(QStringList texts, QWidget *parent)
     : QWidget(parent)
 {
     signalMapper = new QSignalMapper(this);

     QGridLayout *gridLayout = new QGridLayout;
     for (int i = 0; i < texts.size(); ++i) {
         QPushButton *button = new QPushButton(texts[i]);
         connect(button, SIGNAL(clicked()), signalMapper, SLOT(map()));
         signalMapper->setMapping(button, texts[i]);
         gridLayout->addWidget(button, i / 3, i % 3);
     }

     connect(signalMapper, SIGNAL(mapped(const QString &)),
             this, SIGNAL(clicked(const QString &)));

     setLayout(gridLayout);
 }

You can find a PyQT4 example here, however when I have a chance I'll try to add a simple PyQT4 example.

like image 20
Jason Mock Avatar answered Oct 28 '22 21:10

Jason Mock