Reputation: 33813
I want to access to the parent widget elements from child widget.
The parent widget has Qlistwidget
, I want to transfer the selected item from parent to child widget.
I have tried to make a simple example to access to the parent window title, then after that I will try to access to selected item in qlistWidget
.
But the first trying to access the parent widget window title has been failed.
ui->lineEdit->setText(this->parentWidget()->windowTitle());
Now My inquiry is:
qlistWidget
that in
parent widgetUpvotes: 3
Views: 3728
Reputation: 4344
You can access parent's elements, but it's not a right way to go. You should control children instead. Add method to your dialog to set a text, use it to initialize the dialog when you open it and every time QListWidget
selected item is changed.
This approach allows to lessen amount of dependencies, avoid an interdependency, use the dialog in other places of your program.
Not for use but for knowledge:
Firstly, how to access to the parent widget elements like window title.
You do it correctly. Most probably you didn't pass a parent to the constructor of the dialog.
Dialog* dialog = new QDialog(this);
Secondly, how to access to the selected item in qlistWidget that in parent widget
a) You can use dynamic_cast
or qobject_cast
to cast the parent widget to the exact class of the window and use public methods to obtain all needed information.
b) You can inherit your window from an interface with needed methods for obtaining the data and pass this interface to the dialog.
Upvotes: 1
Reputation: 960
Use parent()
function to get a parent of your QObject
. To get children of your parent, use QObject's findChildren
function, passing object name or type as template.
QListWidget
class has selectedItems()
member function, will return selected item.
Use qobject_cast
to cast your QObject
pointers to needed class.
Upvotes: 2