C ++ access to parent widgets from function

I am new to C ++ and Qt, and I am trying to access the widget from the parent class.

Here is my mainwindow.cpp

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

I have another class, and I'm trying to access the widget from "ui" in this class. For example:

 DashBoard::DashBoard( MainWindow *parent ) : QObject( parent ) { } void DashBoard::select( ) { parent->ui->menuSL->setCurrentIndex(0); } 

This gives me an error saying that methods and fields cannot be allowed. But when I put the line parent->ui->menuSL->setCurrentIndex(0); in the constructor, no problem.

Will someone please point out my mistake?

+8
c ++ qt
source share
2 answers

From the code, we can conclude that the DashBoard class inherits QObject . The parent a QObject field is defined as a pointer to a QObject , so when you call parent->ui->menuSL->setCurrentIndex(0); inside the method of the DashBoard class, you assume that QObject defines a member named ui > which is incorrect.

Just highlight the parent this way:

 ((MainWindow*)(parent()))->ui->menuSL->setCurrentIndex(0); 

or this one:

 MainWindow* parent = qobject_cast<MainWindow*>(this->parent()); // check parent is not null parent->ui->menuSL->setCurrentIndex(0); 

You do not see an error in the constructor, because parent is defined as a pointer to an object of the MainWindow class, and then passed to the QObject constructor.

Remember to make ui public and include the header of the automatically generated user interface if you use Qt Designer (in your case, probably "ui_mainwindow.h" ) in the DashBoard cpp file.

NOTE. I'm just trying to answer your question, but I recommend that you look at how you do it. There are several ways to achieve this with a more consistent OO design.

+3
source share

Within the selected method, you are trying to use a variable called parent . But you need a QObject::parent() method.

In addition, you need to give away the parent element of QMainWindow .

 void DashBoard::select( ) { QMainWindow* parent = qobject_cast<QMainWindow>(this->parent()); if (parent == 0) { return; } // or some other error handling parent->ui->menuSL->setCurrentIndex(0); } 

Access to ui is available only to him.

I think you should provide a method inside the MainWindow class that performs the required operation.

+2
source share

All Articles