Reputation: 659
I just started working with Qt, and I'm quite lost with the whole signal-slot system.
I understand the general concept, but I can't understand what is the proper way to design my GUI code.
Is it supposed to be an hierarchy of classes holding pointers to each other? For example, if I have a main window, let's say W1
, with button, B1
, that should open another window, W2
.
It's quite obvious why W1
's class should hold a pointer to B1
, but it seems that I need to hold pointer to W2
's class, in order to connect B1
's clicked()
signal to some custom slot of W2
, and I don't understand why... Isn't the signal-slot mechanism designed to be generic and not specific-instance-wise? What is the proper way of designing this example's code?
Upvotes: 2
Views: 363
Reputation: 620
Connections are always created between instances of class. Signals and slots are mechanism to inform one instances of class B that there was a change or event in instances of class A.
Below is design of class W1 that will show window W2 when button B1 will be clicked. I skipped initialization of class W1, also getting button B1 because there are few ways to create UI of your window. I added check if connection was successful, just for safety (my habit).
class W1 :public QWidget
{
public:
A(QWidget *parent = 0):QWidget(parent)
{
//init
B1 = getB1();
if(!connect(B1,SIGNAL(clicked()),this,SLOT(show_W2())))
qFatal("%s %i connection failed B1->clicked this->show_W2",__FILE__,__LINE__);
}
public slots:
void show_W2()
{
QWidget *W2 = new Window2(this->parent());
//create window
}
protected:
QPushButton *B1;
}
Here is different approach to your example, where class W1 don't now anything about class W2:
class W1 :public QWidget
{
public:
A(QWidget *parent = 0):QWidget(parent)
{
//init
B1 = getB1();
if(!connect(B1,SIGNAL(clicked()),this,SIGNAL(B1_clicked())))
qFatal("%s %i connection failed B1->clicked this->B1_clicked",__FILE__,__LINE__);
}
signals:
B1_clicked()
}
void MainWindow::creatW1()
{
W1 *_w1 = new W1;
if(!connect(_w1,SIGNAL(B1_clicked()),this,SLOT(createW2())))
qFatal("%s %i connection failed _w1->B1_clicked this->show_W2",__FILE__,__LINE__);
}
Upvotes: 1
Reputation: 34391
What is the proper way of designing this example's code?
Create a simple UI with Qt Designer and look at what it generates. That helped me a lot when i was starting with Qt.
Upvotes: 3