Calling the parent ui crashes the application
-
I have a main window widget as -
Ui_WelcomeScreen.h
that's called inWelcomeScreen.h
and.cpp
. In the welcome screen I am usingQListWidget
to which I have added a custom widget calledUi_RecentFiles.cpp
. I have a button in the custom widget which should get the current row count, I tried something like this:auto count = ((WelcomeScreen*)(parent()))->ui->recentFilesView->currentRow(); qDebug() << count;
whenever I do this, the application crashes. I have no idea what's happening. I also tried doing something like:
qobject_cast<WelcomeScreen*>(this->parent())->ui->recentFilesView->currentRow()
Still the same issue. Any idea how to do this. Also, I've checked the children of the current parent from the
Ui_RecentFiles
using -((WelcomeScreen*)(parent()))->children()
- it's giving me a list ofQList(RecentFiles(0x7ff2ade63750, name = "RecentFiles").......)
, I don't think I am actually accessingWelcomeScreen
here. Unless I am wrong.Any idea how to do this?
-
As I wrote before, you are putting the responsibility on the wrong side.
Use a signal that requests the deletion of the item and do the handling in that parent class which is responsible for managing your RecentFiles.
As an analogy, you have an automatic train door issue. The doors do not ask to be closed, they will be when the controller decides it's the right time.
-
Hi,
There are several levels of evil in what you are doing.
The first being to use parent. A child widget should not care about its parent. If there's something that you try to get from the parent it means that you reverted the order of responsibility which is bad because you are creating a tight coupling that should not exist in the first place.
Then static casting like that in that situation is bad as well but that one you fixed with qobject_cast.
You do not check that parent nor the return value of qobject_cast is a non null pointer.Now the question is: what do you do in that child widget that requires information from it's parent ?
-
@akshaybabloo
As @SGaist says. Most likely eitherparent()
isnullptr
or it's not aWelcomeScreen*
. Or something else is wrong. Not too difficult to divide line up and check intermediate results. -
As I wrote before, you are putting the responsibility on the wrong side.
Use a signal that requests the deletion of the item and do the handling in that parent class which is responsible for managing your RecentFiles.
As an analogy, you have an automatic train door issue. The doors do not ask to be closed, they will be when the controller decides it's the right time.
-
@SGaist Ya I was looking at this -> https://stackoverflow.com/questions/50083278/in-qt-how-to-remove-child-widget-from-parent-after-receiving-the-signal-generat. I think this is what I have to do.