开发者

How do I get the value of an object from one window into another window's class with Qt Creator?

This seems like it should be a simple question. I have two QSpinBoxes in my MainWindow, with a push button beside them. The user first selects the dimensions of an array of checkboxes using these spin boxes, then clicks the push button. This pops up a new window with the array of checkboxes in it. The problem I am having though is that when I try to get the value of the spinboxes in my popup window's code, I get a compiler error because these buttons are private. Here is the code:

void DomainGeneration::createBoxes()
{
    int x_dim = MainWindow::ui->xDim->value();
    int y_dim = MainWindow::ui->yDim->value();
......the code......
}

Compiler errors:

'Ui::MainWindow* Ma开发者_如何转开发inWindow::ui' is private within this context

and

object missing in reference to 'MainWindow::ui' from this location

So my question is, how do I access these objects from a different window?


You have two problems:

  1. MainWindow::ui is private
  2. MainWindow::ui is not static, you need an actual instance of a MainWindow to reach it

To solve one, you usually create accessor methods in the MainWindow (or whatever class it is that needs to export some of its state).

To solve two, you need a pointer to your MainWindow instance to call these accessors on.

In your MainWindow class, define something like:

int getXDim() const { return ui->xDim->value(); }

And to get the pointer to your main window, either pass it in to your DomainGeneration's constructor, or into that createBoxes() method, depending on how/where those are called and whether or not you'll need that pointer elsewhere in that class.

Something like:

void DomainGeneration::createBoxes(MainWindow const* main)
{
  int x_dim = main->getXDim();
  ...
}

(Or just pass the dimensions to that methods, obviously.)

(None of this is Qt specific. This is plain C++.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜