How to recycle the memory of QStyle in Qt
-
Hi, everyone,
I'm confused about how the memory of QStyle is recycled in Qt. As I know, there is a parent-child mechanism to manage memory in Qt. Child would be destroyed automatically when its parent is destroyed. But it seems that we have no approach to set parent for QStyle when constructing it. Does it mean we need to call setParent() explicitly after the construction is done? Take a simple example in the following block. It would be appreciated if any suggestion is provided. Thanks in advance.
{ ... QTableView* tableview_1 = new QTableView(this); QProxyStyle* style_1 = new QProxyStyle; tableview_1 ->setStyle(style_1); ... delete tableview_1 ; // how to recycle the memory of style_1 ??? }
-
As mentioned in the documentation styles are not really meant to be used on such granular level. They're quite heavy, so usually there's just one global style set on the app object. Application object takes ownership of the style and deletes it, while individual widgets do not, as you might want to share one style across multiple widgets.
But if you have to use it like that for some reason then yeah, it's just like any other QObject. You either delete it manually or give it a parent via setParent.
Note that the style should not be used anymore at the time it is deleted, so in your example giving ittableview_1
as a parent might not be a good idea, as it would be deleted by the parent while still being used by it. You could either delete the style manually after deleting the widget that uses it or you could connect the widget'sdestroyed()
signal todeleteLater()
slot of the style. -
Thanks for your reply.
The reason that I set a QStyle to a specified table view is that I have a table which contains lots of check boxes and I want all check boxes are locating at the center of table cell. Seemly Qt doesn't provide good solution to meet that requirement easily. Users need do a lot of work by themselves. So, I wrote a style class and set it to the table, which is to adjust object's position in the table. That style is only to be used by a specified table.
BTW, it's really a common requirement to make content locate at center in the table. Why Qt can't support it with an easy way?
-
you can using Grid Layout or any other Layouts as provided by Qt to position all your checkboxes in the table center. you need to wrap them in a layout or Groupbox and then use them as WidgetItem.
Use QTableWidget instead of QTableView as QTableView is meant only for viewing purpose of text or data not controls.
Use the geometry property of each checkbox or you can set its position directly instead of positioning it using QStyle.