QButton and QLabel
The source code of this example can be found here: https://github.com/KKyang/Qt-Tutorial/tree/master/01-Basic/QT_Button_and_label/QT_Button_and_label
In this tutorial, I'll show you how to create an application with a QButton and a QLabel. When the user press the button, the label below will change its text.
Qt Designer
The first few examples will go through the programming interface design process. If you want to add a QButton and a QLabel, just drag the widgets to your application. The third step in the picture aligns the button and the label vertically.
When your design is complete, right-click the button and choose "Go to slot...". Choose the clicked()
signal (*1).
Code
After you complete the action, you will be switched back to the mainwindow.cpp with this auto-generated code segment.
void MainWindow::on_pushButton_clicked()
{
}
And also in mainwindow.h
private slots:
void on_pushButton_clicked();
This is where the application received the signal (so called slot) fired by QButton. The pushButton is the object name of the QButton. So if you change the QButton's object name later, you'll have to correct the name in the slot function.
In order the change the words shown in the label, let's look at some functions of the QLabel:
ui->label->text();
ui->label->setText(QString);
The first line returns the current text of the label, and the second line sets the text output. The following code will do the trick:
void MainWindow::on_pushButton_clicked()
{
if(ui->label->text()=="This is a label")
{
ui->label->setText("This is not a label");
}
else
{
ui->label->setText("This is a label");
}
}
If you want your QLabel outputs text when start up, you can add one line to the constructor of the mainwindow class.
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
//This line
ui->label->setText("This is a label");
}
At last, compile your project and your done!
Note 1: Signals and Slots is a very useful construct that only exists in Qt. It simplifies the communication between objects. Just imagine you are playing baseball, I throw a ball (signal) and you catch (slot). I'll introduce this in the next chapter.