I am just starting a Qt tutorial, and I am also a beginner level of C++. In the Qt tutorial, there is an example that use statement to set the button's text:
ui->pushButton->setText("Hello");
I understand that we can use ->
operator to allow an pointer to access member of class. In this case, pushButton->setText("Hello")
, but I just don't understand the meaning of ui->pushButton
, I search some answers explained that the ui
hold the reference of the pushButton
, but how this can be done? pushButton
is a pointer to the object, is not a member of the class, can we use ->
to put the object address to the ui
pointer?
Sorry for my bad English language, I may confused you. I wish someone can give me a clear explanation, thanks in advance.
The ui
pointer is generated from the xml you create with the form editor of QT Creator.
You can find the autogenerated header file in the output directory. For example the main window has a ui_mainwindow.h
. This file is created after you run qmake
. If you use QT Creator this is done automatically.
Here is an example of an autogenerated ui
:
class Ui_MainWindow
{
public:
QWidget *centralWidget;
QPushButton *pushButton;
QMenuBar *menuBar;
QToolBar *mainToolBar;
QStatusBar *statusBar;
...
};
ui
is a Ui_MainWindow *
so you can use ->
on it to access the members of the Ui_MainWindow
class, like pushButton
.
pushButton
is a QPushButton *
so you can use ->
on it to access the members of the QPushButton
class, like setText()
.
ui->pushButton->setText("Hello")
is equivalent to this:
Ui_MainWindow * ui = new Ui_MainWindow;
...
QPushButton * btn = ui->pushButton;
btn->setText("Hello");
Some corrections:
->
does not allow a pointer to do things :)
->
is just an operator to access members of a class or struct, and must be applied to a pointer. If you have an instance you must use .
operator to access the members.
Please see: operators.
Finally a similar question you should read.
The "arrow" operator ->
is used to dereference pointers to objects to get their members. So if you have a pointer an object in the variable ui
and the object has a member pushButton
then you can use ui->pushButton
to access the pushButton
member. If the pushButton
member in turn is a pointer to an object then you use ->
again to access its members, like ui->pushButton->setText("Hello")
.
Using the "arrow" operator is basically just syntactic sugar for the dereference (unary *
) and dot (.
) member access operator.
So the statement
ui->pushButton->setText("Hello");
could also be written as
(*(*ui).pushButton).setText("Hello");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With