As a GUI deverloper, Max is always looking for a elegant way to dynamically determine the appearance of widgets.
For example, now we have a wonderful recipe software, which can allow user input the name and display its ingredient. I want to open a dialog to show the ingredients of a recipe, let's say IngredientDialog. According to the recipe name, program retrieves the associated ingredients from database in the background. Assume that each ingredients are displayed in a QLabel. Obviously, we don't know the number of ingredients until the moment to open the dialog.
Solution 1: Everytime create a completely new IngredientDialog. Actually, it isn't a bad idea. Clear, easy but may be slow, because you need to remove everytime the old IngredientDialog and create a new one, in which a number of QLabel objects are created according to current recipe.
Solution 2: IngredientDialog is created once. Everytime it is open, the IngredientDialog cleans up the old QLabels and creates a new collection of QLabel, the others widgets keep unchanged. Looks very efficient. But frequent delete and new operations may lead to a memory leak, especially if the widgets are complicated or are implemented from the third parts.
Solution 3: Let's return back to the old style of C: allocate all the required variables and memory at the beginning of function and avoid to reallocate memory afterwards. For this example, IngredientDialog create enough QLabels in its constructor, but dynamically determine it is shown or hiden when the dialog is opened.
Seldomly, if a speical recipe has even more ingredients, the more QLabels will be created, but it is really seldom.
Tips: for a frequrently redrawn widget, it is a good idea to perserve the pointers of every created widgets and layout. In such way, the widgets can be easily altered, relocated or deleted among the layouts.
No comments:
Post a Comment