Tuesday, July 6, 2010

signals and slots

In the last exercise "Slider and SpinBox", the slider and spinBox have no relationship at all. Here, we are going to add connect between them. When any one of the slider and the spinBox value changed, it will send a SLOT of valueChanged to the SLOT of the other, and update its value.




#include <QtGui>

int main(int argc, char* argv[])
{
QApplication app(argc, argv);

QWidget* mainwindow = new QWidget();
QVBoxLayout* mainlayout = new QVBoxLayout();

QSlider* slider = new QSlider(Qt::Horizontal, mainwindow);
slider->setRange(0, 100);

QSpinBox* spinBox = new QSpinBox(mainwindow);
spinBox->setRange(0, 100);

QObject::connect(slider, SIGNAL(valueChanged(int)), spinBox, SLOT(setValue(int)));
QObject::connect(spinBox, SIGNAL(valueChanged(int)), slider, SLOT(setValue(int)));

mainlayout->addWidget(slider);
mainlayout->addWidget(spinBox);

mainwindow->setLayout(mainlayout);
mainwindow->show();
return app.exec();
}


next: Define custom signals and slots