0

I need a QMainWindow layout to change depending on the number of cores. Therefore I set it manually (not using the Design mode).

My question is: After this layout was created, how can I refer to the widgets it contains?

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

    //...
    buildLayout();
    //...

    // Now I'd like to use something like this:
    // ui->threadingTable->...
    // However, it's not the member of ui
}

void MainWindow::buildLayout()
{
    QWidget *window = new QWidget(this);

    QTableView *threadingTable = new QTableView(window);
    //...

    QGridLayout *layout = new QGridLayout(window);
    layout->addWidget(threadingTable, 0, 0);
    //...

    window->setLayout(layout);
    this->setCentralWidget(window);
}

I can get the QLayoutItem out of this->centralWidget(). Or I can make all widgets in layout members of MainWindow class and access them directly.

However, I feel that neither of these is the right way.

Is there a way to pass the widgets to ui? So that I could access them by calling ui->threadingTable

  • In my opinion there's nothing wrong in making the widgets also members of the "main" class. Of course you don't usually need to access all of them and signals might be connected before adding them to the layout. – juzzlin Sep 20 '15 at 15:45

1 Answers1

0

Both options are fine. It is possible to get pointer to threadingTable from the main class member or directly from the objects hierarchy:

qDebug() << qobject_cast<QGridLayout *>(this->centralWidget()->layout())->itemAtPosition(0, 0)->widget();
qDebug() << this->centralWidget()->layout()->itemAt(0)->widget();

Of course, null verification may be required. You can also check this question QGridLayout: Getting the list of QWidget added.

The class Ui::MainWindow is automatically generated from the .ui xml form that can be generated in the Design mode: "Using a Designer UI File in Your Application"

Since the layout is constructed manually the .ui file and the ui instance is not needed at all. You can remove them from your project.

On the other hand, it is possible to use custom widgets even in the Design mode in .ui forms. So, if you need some tricky object you can build the entire form in handy Design mode and then, for example, the standard QTableView may be promoted to your CustomTableView that is inherited from QTableView. That custom class may implement some special behavior.

Community
  • 1
  • 1
Orest Hera
  • 6,706
  • 2
  • 21
  • 35