Search code examples
c++qtqwidget

Qt Widget class' parent is always NULL


I have a custom QWidget class called VideoWidget that looks something like this:

VideoWidget::VideoWidget(QWidget *parent) : QWidget(parent)
{
    ClickableLabel *smallRed = new ClickableLabel(this)
    //...
    QObject::connect(smallRed,SIGNAL(clicked()),this,SLOT(removeVideo()));
}
void VideoWidget::removeVideo(){
    //...remove a file
    MainWindow* myParent =  qobject_cast<MainWindow*>(this->parent());        
    QListWidget* myList = myParent->getList();
    QListWidgetItem* item = myList->currentItem();
    myList->removeItemWidget(item);
}

The VideoWidget widgets are created in my MainWindow class with the argument this and then added to a QListWidget. When clicking on the smallRed label in my VideoWidget I want my program to delete a file and then run the code to remove the widget from my QListWidget in my MainWindow. My problem is that the line MainWindow* myParent = qobject_cast<MainWindow*>(this->parent()); always returns NULL and I don't understand why. Any help is much appreciated.


Solution

  • See this code, I think you have something similar:

    for(int r=0;r<2;r++)
    {
        QListWidgetItem* lwi = new QListWidgetItem;
        ui->listWidget->addItem(lwi);
        ui->listWidget->setItemWidget(lwi, new QCheckBox(QString("checkBox%1").arg(r),this));
        qDebug() 
        << ui->listWidget->itemWidget(lwi)->parent()
        << ui->listWidget->itemWidget(lwi)->parent()->parent()
        << ui->listWidget->itemWidget(lwi)->parent()->parent()->parent()
        << ui->listWidget->itemWidget(lwi)->parent()->parent()->parent()->parent();
    }
    

    As you can see I set this as a parent, but my first parent is qt_scrollarea_viewport too, because Qt reparent your widget. Output of my code is:

    QWidget(0x27c64260, name = "qt_scrollarea_viewport") 
    QListWidget(0x27c64240, name = "listWidget") 
    QWidget(0x264bedd8, name = "centralWidget") 
    MainWindow(0x28fdcc, name = "MainWindow")
    

    If you have same structure then use a few parent() calling

    Yes, it is not very beautiful but as far as I know Qt has no something like findParent, only findChildren

    As thuga suggested it works but it is not very good, your VideoWidget should not know about MainWindow. You should use signals and slots. Just emit signal from VideoWidget and catch this signal in MainWindow (write special slot and remove your item in this slot). It will be better than this magic with parent().