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.
See this code, I think you have something similar:
As you can see I set
thisas a parent, but my first parent isqt_scrollarea_viewporttoo, because Qt reparent your widget. Output of my code is:If you have same structure then use a few
parent()callingYes, it is not very beautiful but as far as I know Qt has no something like
findParent, onlyfindChildrenAs
thugasuggested it works but it is not very good, yourVideoWidgetshould not know aboutMainWindow. You should use signals and slots. Just emit signal fromVideoWidgetand catch this signal inMainWindow(write special slot and remove your item in this slot). It will be better than this magic withparent().