Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ accessing parent widgets from a function

Tags:

c++

qt

I am new to C++ and Qt and I am trying to access a widget from a 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 am trying to access a widget from "ui" in that class. Like so:

DashBoard::DashBoard( MainWindow *parent ) : QObject( parent ) 
{
}

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

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

Would someone please point out my mistake?

like image 619
user2444217 Avatar asked Sep 06 '13 04:09

user2444217


1 Answers

From the code one can infer that the class DashBoard inherits QObject. The parent field of a QObject is defined as a pointer to a QObject so when you call parent->ui->menuSL->setCurrentIndex(0); inside a method of the class DashBoard you're assuming that QObject defines a member called ui which is not true.

Just cast 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);

In the constructor you don't see the error because parent is defined as a pointer to an object of the class MainWindow and then passed to the QObject's constructor.

Don't forget to make ui public and to include the auto generated UI header if using 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 encourage you to review the way you're doing this. There are several ways of achieving the same with a more consistent OO design.

like image 165
mhcuervo Avatar answered Sep 27 '22 22:09

mhcuervo