" operator to access pointers to an object pointer? I am just starting a Qt tutorial and I am also a beginner in C ++. The Qt tuto...">

Can I use the "->" operator to access pointers to an object pointer?

I am just starting a Qt tutorial and I am also a beginner in C ++. The Qt tutorial provides an example of using instructions to set the button text:

ui->pushButton->setText("Hello"); 

I understand that we can use the -> operator to give the pointer access to the class member. In this case, pushButton->setText("Hello") , but I just do not understand the meaning of ui->pushButton , I was looking for answers to some answers explaining that ui contains a pushButton link, but how can this be done? pushButton is a pointer to an object, is not a member of a class, can we use -> to put the address of an object in a ui pointer?

Sorry for my bad English, I can confuse you. I want someone to give me a clear explanation, thanks in advance.

+8
c ++ pointers qt
source share
2 answers

The ui pointer is created from the xml you created using the QT Creator form editor.

You can find the auto-generated header file in the output directory. For example, the main window has ui_mainwindow.h . This file is created after qmake starts. If you use QT Creator, this is done automatically.

Here is an example of an auto- ui :

 class Ui_MainWindow { public: QWidget *centralWidget; QPushButton *pushButton; QMenuBar *menuBar; QToolBar *mainToolBar; QStatusBar *statusBar; ... }; 

ui is Ui_MainWindow * , so you can use -> to access members of the Ui_MainWindow class, such as pushButton .

pushButton is a QPushButton * , so you can use -> to access members of the QPushButton class, such as setText() .

ui->pushButton->setText("Hello") equivalent to this:

 Ui_MainWindow * ui = new Ui_MainWindow; ... QPushButton * btn = ui->pushButton; btn->setText("Hello"); 

Some fixes:

-> does not allow the pointer to do anything :)

-> is just an operator for accessing the elements of a class or struct and should be applied to the pointer. If you have an instance, you should use a statement . to access members.

See: operators .

Finally, a similar question you should read.

+8
source share

The arrow -> operator -> used for pointers to dereferencing objects to get their members. Therefore, if you have a pointer to an object in the ui variable, and the object has a pushButton member, then you can use ui->pushButton to access the pushButton element. If the pushButton member, in turn, is a pointer to an object, then you again use -> to access your members, for example ui->pushButton->setText("Hello") .

Using the arrow operator is basically syntactic sugar for the dereference operator (unary * ) and period ( . ).

So statement

 ui->pushButton->setText("Hello"); 

can also be written as

 (*(*ui).pushButton).setText("Hello"); 
+3
source share

All Articles