Qt Widget

Double click mainwindow.ui, Qt creator will bring you to Qt Designer.

If you want to use a widget, just simply drag and drop the widgets in the tool box.

To add an action to a widget, right-click the widget (QCombobox) and choose Go to slot.... Qt will ask you to choose a templat signal. Of course you can write your own signal, we will talk about this in Chapter 3.

In this case, we will choose the signal currentIndexChanged(int). This signal triggers when the index of the combo box changed, and it returns the current index.

When the signal is chosen, Qt will switch back to the editor. You will find a new code segment as below. You can add any behavior here.

void MainWindow::on_comboBox_currentIndexChanged(int index)
{

}

For example, when I change a selection of the combo box, I wish I can output the choice on a label.

void MainWindow::on_comboBox_currentIndexChanged(int index)
{
    ui->combo_label->setText(QString::number(index) + " " +ui->comboBox->currentText());
}

Widget label has a public slot void setText(const QString &). (We'll explain slot later. Now you can see slot as a kind of function.) We can put QString (a Qt format of std::string with more functions) into the function and make the label to show the words we gave them. QString is able to connect with a plus sign. It can also turn numbers into a QString by function QString::number(int). To get the text of the current combo box index, we can call function currentText(). And here's the final result:

You can see the label shows the index also the text of the combo box.

results matching ""

    No results matching ""