ARM
ARM

Reputation: 1550

Access widgets of a QDockWidget from within the QMainWindow

In my QMainWindow scope I have an instance of a class AgilentSweeper which inherits QDockWindow, and initialize and display it with:

sweeper = new AgilentSweeper(this);
addDockWidget(Qt::RightDockWidgetArea,sweeper);

This class has a Qt Creator-made .ui form which has several widgets in it and the constructor looks like:

AgilentSweeper::AgilentSweeper(QWidget *parent) :
    QDockWidget(parent),
    ui(new Ui::AgilentSweeper)
{
    ui->setupUi(this);

}

where Ui::AgilentSweeper *ui is public.

From other functions in the AgilentSweeper scope I can access the AgilentSweeper widgets and do things like double power = ui->powerSpinBox->value(); normally. However, I can't figure out how to access the AgilentSweeper widgets from within the scope of the main Ui. It seems like this should be possible because sweeper is a member I thought I should be able to do something like double power = sweeper->ui->powerSpinBox->value();, but despite messing around with it for a while I can't figure out how to access anything from sweeper's ui. I can think of several work-arounds, but this seemed like it should be possible.

Upvotes: 1

Views: 438

Answers (1)

Valentin H
Valentin H

Reputation: 7458

ui Object is defined as private member of AgilentSweeper by default. So normally, you can't access it. Some solutions:

  1. very bad: declare QMainWindow as friend
  2. bad: Change in AgilentSweeper.h private: by public: for the Ui::AgilentSweeper
  3. one I would prefer:for each method of your UI-widgets you want to expose, create a public method in AgilentSweeper.h

So you can access the spinbox-value by

//in AgilentSweeper.h
double powerSpinBoxValue()
{
    return ui->powerSpinBox->value()
}

//call from outside:
double power = sweeper->powerSpinBoxValue();

EDIT Explanation for 2

The object Ui::AgilentSweeper *ui is defined in AgilentSweeper.h usinf forward declaration. So in a file including AgilentSweeper.h alone, no information is given, how to create an instance of the object and which methods it provides. This information is provided by autogenerated file ui_AgilentSweeper.h. so in order to use the way 2, include also ui_AgilentSweeper.h.

Why is this solution bad? It looks so flexible right?

In the first line exposing members as public is bad. A user could delete the instances: e.g. delete sweeper->ui->powerSpinBox.

Besides, there is no way to log or lock the access to the member objects.

Upvotes: 1

Related Questions