PDA

View Full Version : Singal and Slot related simple problem!!!



eklavay_tonoy
29th September 2015, 15:41
Hello to All,

I just have started to learn Qt with a very little C++ knowledge. Anyhow, I am having problem to slove a very simple problem. I am having problem with "Signal and Slot" understanding.

Task:
1. By selecting an item from Combo Box
2. That Item will be showed by a Label in the mainwindow.

It is very simple thing but I am not able to solve it.

Here below is my code:

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

connect(ui->comboBox,&QComboBox::activated,ui->label,&QLabel::setLabelValue);

}

MainWindow::~MainWindow()
{
delete ui;
}

MainWindow::setLabelValue()
{
ui->label->text() = ui->comboBox->currentText();
}

It is not working. Will there be anyone to suggest me so that I could solve it.

Thanks in advance!

yeye_olive
29th September 2015, 16:12
First of all, could you please describe what "is not working"? For instance, explaining "my program cannot be compiled; the compiler outputs the following error message: ..." or "my program runs, but has behavior X when I expected behavior Y" would be very helpful.

I expect the line

connect(ui->comboBox,&QComboBox::activated,ui->label,&QLabel::setLabelValue);
to produce a compilation error. Is that right? I can see several problems:

The reference to QComboBox::activated is ambiguous, because the signal is overloaded; you can use static_cast to specify a type and select the right overload.
There is no QLabel::setLabelValue method. The method is in your own MainWindow class.
The object whose slot is connected should be the MainWindow instance, not the QLabel ui->label.


You could fix this line and go through with your original plan (connect the combobox' activated signal to a slot in the main window that sets the label's text), but you can do something simpler: connect the combobox' QComboBox::activated(const QString &) signal to the label's setText(const QString &) slot. The signal will directly pass the text of the selected item to the slot setting the label's text. This should look something like:

connect(ui->comboBox, static_cast<void (QComboBox::*)(const QString &)>(&QComboBox::activated), ui->label, &QLabel::setText);
(I have not tested or even compiled this code, it may well be broken). Notice the use of static_cast to disambiguate between QComboBox::activated(const QString &) and QComboBox::activated(int).

anda_skoa
29th September 2015, 17:17
Or use QComboBox::currentTextChanged (unless the combobox allows user input).
Or use the SIGNAL/SLOT macro based connect().

Cheers,
_

Infinity
29th September 2015, 17:49
Additionally, you can't set the label text with ui->label->text(). You need to use the setText() method. C++ is not C# where you set "properties" using that syntax.

As already posted, you can connect to setText directly.