laxer
laxer

Reputation: 760

QT retrieve custom widget from layout

I have a scroll area with a layout that has 8 of the same custom widgets that have been added to it. This custom widget has a getter function that will return a value. My question is how to get back that original custom widget so I can call the getter function to retrieve the data it stores?

I have added the custom widget to the layout this way:

for (int var = 0; var < 9; ++var) {
    calcRow *CalcWidget = new calcRow(this, &js, KeyList, SizeList);
    connect(CalcWidget, &calcRow::testSignal, this, &MainWindow::getRowData);

    ui->scrollArea_layout->layout()->addWidget(CalcWidget);
}

Where I am stuck:

void MainWindow::getRowData()
{
    for (int i = 0;i < ui->scrollArea_layout->layout()->count() ;++i ) {
        QWidget *row = ui->scrollArea_layout->layout()->itemAt(i)->widget();

        if(row != NULL)
        {
            std::cout << row->"SOMETHING TO GET CALCROW WIDGET"  <<std::endl;
        }
    }
}

Upvotes: 0

Views: 498

Answers (2)

laxer
laxer

Reputation: 760

For anyone else that will find this in the future, the comments helped a bunch and I ended up using static_cast. My final code looks like this:

void MainWindow::getRowData()
{
    for (int i = 0;i < ui->scrollArea_layout->layout()->count() ;++i ) {
        QWidget *row = ui->scrollArea_layout->layout()->itemAt(i)->widget();

        calcRow *rowConverted = static_cast<calcRow*>(row);

        if(row != NULL)
        {
            std::cout << rowConverted ->getData()  <<std::endl;
        }
    }
}

Upvotes: 0

jdfa
jdfa

Reputation: 689

Usually it's not the best structure for your code, any layout change might break your implementation. For example this solution will not work if you will have multiple calcRow widgets.

To make it better, you can pass required parameters which you want use inside getRowData as a parameters of testSignal signal.

Or just simplify it even more with lambda:

for (int var = 0; var < 9; ++var) {
    calcRow* CalcWidget = new calcRow(this, &js, KeyList, SizeList);
    connect(CalcWidget, &calcRow::testSignal, [CalcWidget]() 
        {
        std::cout << CalcWidget->"SOMETHING TO GET CALCROW WIDGET" << std::endl;
        });

    ui->scrollArea_layout->layout()->addWidget(CalcWidget);
}

Upvotes: 1

Related Questions