How to append CustomQWidget from QVBoxLayout into a QVector

Viewed 33

I'm trying to get every CustomQWidget i added to the layout and insert them into a QVector so i can sort them.

void MainWindow::onFilenameClick()
{
    QVector<CustomQWidget*> qv;

    for(int i = 0; i < ui->widgets_layout->count(); i++) {
        QWidget *widget = ui->widgets_layout->itemAt(i)->widget();
        if(widget != nullptr) {
            qv.append(widget);
        }
    }
    std::sort(qv.begin(), qv.end(), sort_by_filename());
    update_ui(qv);
}

The problem is that i keep getting the error message

no matching member function for call to 'append'
candidate function not viable: cannot convert from base class pointer 'QWidget *' to derived class pointer 'CustomQLabel *const' for 1st argument
candidate function not viable: cannot convert from base class pointer 'QWidget *' to derived class pointer 'CustomQLabel *' for 1st argument
candidate function not viable: cannot convert from base class pointer 'QWidget *' to 'const QVector<CustomQWidget *>' for 1st argument

I've already tryed to static_cast the CustomQWidget to QWidget but nothing has changed.

qv.append(static_cast<QWidget*>(widget));

And I also tried with

qv.push_back(widget);
qv.insert(i, widget);

Here's the CustomQWidget.h

class CustomQWidget : public QWidget
{
  Q_OBJECT
public:
...
private:
  Ui::CustomQWidget *ui;
...
};

I really don't know what to do, please help me

1 Answers

You state...

I've already tryed to static_cast the CustomQWidget to QWidget but nothing has changed.

qv.append(static_cast<QWidget*>(widget));

But why? widget is already of type QWidget * and qv is declared as...

QVector<CustomQWidget *> qv;

You need something like (untested)...

QVector<CustomQWidget *> qv;

for(int i = 0; i < ui->widgets_layout->count(); ++i) {
    if (auto *custom_widget = dynamic_cast<CustomWidget *>(ui->widgets_layout->itemAt(i)->widget())) {
        qv.append(custom_widget);
    }
}

Alternatively, as you're using Qt, you can make use of qobject_cast rather than dynamic_cast...

QVector<CustomQWidget *> qv;

for(int i = 0; i < ui->widgets_layout->count(); ++i) {
    if (auto *custom_widget = qobject_cast<CustomWidget *>(ui->widgets_layout->itemAt(i)->widget())) {
        qv.append(custom_widget);
    }
}
Related