Qt 將一個Widget(子)從某個Widget(父)中移除的方法

        其實很簡單,但是對於我來說解決了一個一直困擾我的問題。Qt很多Widget並沒有提供delete或者remove的方法。 

        如果不需要子Widget時,直接delete,用deleteLater()比較好。如果還需要使用子Widget,使用setParent()可以讓子Widget從父Widget中剝離出來。無論是直接delete,還是setParent,都會通知父Widget,父Widget都會更新自己的內容。

           下面我把英文原文和相關鏈接附上。


It's not clear to me if you want to preserve the widget and put it somewhere else, or if you want to destroy the widget.

  • Destroying the widget: If you can get a pointer to the widget, you can simply delete it. The splitter willsafely be notified that its child isbeing deleted and will remove itfrom itself.

  • Preserving the widget: If you grab the pointer to the widget, you can simply set its parent to some other widget and add it to another widget's layout and it will show up there. This is safe because the QSplitter will be notified that one of its children is being reparented.

If you want to set the parent to NULL (cjhuitt's answer) be aware that you are now responsible for cleaning up that memory because the widget no longer has a parent.


相關鏈接:http://stackoverflow.com/questions/371599/how-to-remove-qwidgets-from-qsplitter

                    http://stackoverflow.com/questions/20328437/remove-widget-from-qsplitter


發佈了130 篇原創文章 · 獲贊 13 · 訪問量 28萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章