开发者

How to change/swap the layout of a widget?

开发者 https://www.devze.com 2023-01-16 05:20 出处:网络
I am working on an application in which I need to change the layout of my current tab when a radio button is pressed.

I am working on an application in which I need to change the layout of my current tab when a radio button is pressed.

I am using the following code to swap the layout:

changed_layout = new QVBoxLayout;
label1 = new QLabel(string);
delete main_layout;
changed_layout->addWidget(label1);
setLayout(changed_开发者_运维技巧layout);

But when I click the button the software exits (crashes).


You shouldn't try to directly delete QObjects with delete, call ojbect->deleteLater() and set your pointer to null. The Qt framework will safely delete the object after any slots have been exited and control has returned to the event loop.

In your code, change the line delete main_layout; to:

main_layout->deleteLater();
main_layout = NULL;

Update: The comment from Steve S is correct. To quote Qt docs for setLayout()..

If there already is a layout manager installed on this widget, QWidget won't let you install another. You must first delete the existing layout manager (returned by layout()) before you can call setLayout() with the new layout.layout.

Since setLayout() is a special case of reparenting widgets, we must delete the old layout first and then set the new layout. We would have to be very sure of the signal/slot call stack we are in to call delete().

An alternative would be to setup the new layout as much as possible and then connect a slot to the old layouts destroyed() signal and then call deleteLater() on it. In the slot for the destroyed() signal you should be able to call setLayout() with the new layout.

If this sounds complicated, it's because it is. Changing and destroying layouts at runtime is unusual. If I found that I had to do something like this, I would probably create something like a gridLayout at the top of the hierarcy with the different layouts I would need set inside it and then move the child widgets from layout to layout without having to create and destroy them at runtime.

0

精彩评论

暂无评论...
验证码 换一张
取 消