Qt Signals and Slots, Connecting and Disconnecting

Slots, slots everywhere...
by Ramon Talavera

Qt connects widgets by means of a nice designed scheme based on the idea that objectS may send signalS of different typeS to a single object instance:


This is a screenshot of the example code running. The main application creates dialogs A and B and then connects the signal from A to the signal slot in B.


I cannot believe I have clicked it 100 times to show you that it works...



Declaring the signal:

 A declares to be able to send signals of type 'somebodyClicked':

class ObjectADialog : public QDialog {
Q_OBJECT
public:
explicit ObjectADialog(QWidget *parent = 0);
~ObjectADialog();


signals:
     void somebodyClicked(QString who);


protected:
void closeEvent(QCloseEvent *event);
private slots:
void on_pushButton_clicked();
private:
Ui::ObjectADialog *ui;
};

Declaring the slot:

B declares to contain a slot method for signals to connect to:
 
class ObjectBDialog : public QDialog
{
    Q_OBJECT
 public:
    explicit ObjectBDialog(QWidget *parent = 0);
     ~ObjectBDialog();
 public slots:
     void seemsThatSomebodyHasClicked(QString whodid);
 protected:
     void closeEvent(QCloseEvent *event);
 private:
     Ui::ObjectBDialog *ui;
     int signaledTimes;
 };

Enabling and disabling the signal:

MainWindow connects A to B by calling "connect(A,signal,B,slot)" that could be 
read as 'A signals B in the slot' (ouch!):
 
void MainWindow::connectAB()
{
    QObject::connect(
                    objectADialog,
                    SIGNAL(somebodyClicked(QString)),
                    objectBDialog,
                    SLOT(seemsThatSomebodyHasClicked(QString)));
    connected=true;
} 
 
 
and disconnects the signal with:
void MainWindow::disconnectAB()
{
    QObject::disconnect(objectADialog,
                        SIGNAL(somebodyClicked(QString)),
                        objectBDialog,
                        SLOT(seemsThatSomebodyHasClicked(QString)));
    connected=false;
} 
 
disconnect follows the same syntax as connect so "disconnect(A,signal,B,slot)"
could be read as: A no longer signals B in the slot. B can stop suffering now.
 

Emitting the signal:

A emits the signal by calling emit, all objects whose slots have been connected 
to that type of signal will be, emmm signaled then:

void ObjectADialog::on_pushButton_clicked()
{
    emit somebodyClicked(QString("Object A"));
}
 
 
Download the example code. 


ramon.talavera@gmail.com

Comments

Post a Comment

Popular posts from this blog

Vaadin 7: Detect Enter Key in a TextField

JAVA JPA WITH HIBERNATE AND H2 Tutorial