Penalty of using QGraphicsObject vs QGraphicsItem? - qt

I currently have a hierarchy of items based off of QGraphicsItem.
I want to move to QGraphicsObject instead so that I can put properties on my items. I will not be making use of signals/slots or any other features of QObject.
I'm told that you shouldn't derive from QObject because it's "heavy" and "slow".
To test the impact, I derive from QGraphicsObject, add a couple properties to my items, and look at the memory usage of the running app. I create 1000 items using both flavors and I don't notice anything more than 10k more memory usage.
Since all I am adding on to my items are properties, is it safe to say that QObject only adds weight if you are using signals/slots?

I think it depends on what you mean by weight. If you're not worried about the additional memory required nor all the extra methods and things that come with QObject, which sound like baggage in your case, then yes.
But, if all you need is a way to store some additional information, why not subclass QGraphicsItem and add a method or two that allow you to store the necessary data? By doing so, I think you'll better communicate the intent of your code, which seems more important than all of the above.

How about performance? There is extra cost in QGraphicsObject when calling setX/setY, and so on. You can go to QGraphicsItemPrivate::setPosHelper and find more details.

Related

What's the purpose of inheriting QAbstractTableModel, QAbstractListModel, etc. for ListView, GridView and TableView

I could have a simple QVector, QList, etc. of QObject to present in ListView, GridView and TableView and add/edit/remove items in/from those View. To me using QVector, QList, etc. of QObject* is the easiest way to accomplish the ultimate goal. What's the real benefit of inheriting QAbstractTableModel, QAbstractListModel, etc.? In WPF we've VirtualizingStackPanel and some properties to boost performance in such type of View. Does inheriting those Abstract..Model serve the same purpose or either way (inheriting or using plain QVector/QList), performance will be same?
The advantages of QAbstractItemModel and subclasses are mainly increased performance when handling larger lists, and increased flexibility by using proxy models:
Partial updates: A model can tell the view that single rows or ranges of rows were inserted, moved, removed or updated which then the view can act upon in a smarter way than throwing away and rebuilding everything. The cost of inserting an item in the middle of 10k other items is cheap, for example.
Lower overhead: A large list of, say, 50k QObject*s would have a major overhead, both in cost for the objects themselves and in handling all the signal/slot connections for handling the property updates.
A model can act as an adapter to an already existing data structure, without the need to hold all the data in the model (although that can be tricky in practice, to guarantee correctness/consistency)
Lazy-loading: The model can load data on demand as the user is navigating the view, without having to have all data already available (see fetchMore()/canFetchMore()).
Flexibility through proxies: QAbstractProxyModel and subclasses (in particular, QSortFilterProxyModel) allow stacking of models to filter/sort/modify the data in the original model. With QSortFilterProxyModel sorting and filtering is usually much simpler to implement (and without changing the original data/model) than implementing it manually for a QList. Simple modifications like changing the returned data for a certain role can be implemented by subclassing QIdentityProxyModel.
More complex data structures: QAbstractItemModel also allows for trees (tricky to implement though) and tables. These are more often used in "traditional" (QWidget-based) desktop UIs than in embedded/mobile touch UIs though.

QQmlListProperty vs QAbstractListModel

I am trying to understand how one would choose whether to use a QAbstractListModel or a QObject with a QQmlListProperty.
Given that the QQmlListProperty handles the "roles" functionality that would have to be written using the QAbstractListModel, it seems like the less tedious route.
I can't tell if most people suggest using QAbstractListModel simply because it has been around longer or if it is the better choice for some reason.
Nor have I been able to find any discussion of the trade-offs between the two options. This question was brought up during a Qt Developer Days talk discussing QAbstractListModel, but the answer was along the lines of "that would also work".
A model implementation will generally be more efficient to work with a view. When you expose a "dumb list" to use a model, every time the model changes the whole view is reconstructed, whereas with a model only the changes are updated. If you have a lot of items there will be tangible performance overhead.
You could use a list for a model, and you could use a model for a list, but when you want optimal performance, you should use a list for a list, and a model for a model.

qt performance – OpenGL

i wan't to use Native OpenGL in the paint function of my widgets(QPainter), to improve performance.
i saw that there is function QPainter::begin/endNativePainting(), that can help me.
but i can't find examples for that...
i wanted to know if those functions are low cost, or evry use of them reduce performance?
2.can i define beginNativePainting() and endNativePainting(), in general for all the widgets i use, instead of using that in every paint function i have.
tnx for any help....
There is some basic example code right in the documentation: http://doc.qt.io/qt-4.8/qpainter.html#beginNativePainting
The functions themselves should be fairly low-cost, but calling them might still cause a noticeably overhead, because Qt has to flush its internal painting queue on the beginNativePainting() call and probably has to assume that everything is changed as soon as endNativePainting() is called.
For the second part I am not sure if I understand what you are aiming at. Basically if you have a QPainter object, you can call beginNativePainting() once. But you have to match it with an endNativePainting() call. So the usual place would be the paint() method.
Qt is using a range of OpenGL functionalities to implement its 2D painting, including custom shaders and various frame buffers. It puts OpenGL into a pretty messy state.
beginNativePainting / endNativePainting are there to allow Qt's drawing engine to save this context and retrieve it once the user is done drawing.
It would have been nice to have the xxxNativePainting methods do the contrary (i.e. automatically save and restore user configuration of OpenGL), but since Qt allows to call OpenGL primitives directly, saving the global state is nigh impossible without tons of code and potential serious performance hit.
Instead, these methods simply save Qt's internal OpenGL state and, rather than having user code start in a configuration that would be meaningless anyway (and likely to change with each new Qt release), reset OpenGL to a "neutral" state.
It means that, inside a begin/end section, you will start with a clean slate: no shader linked, no vertex array, most of global parameters reset, etc.
Contrary to a simple QGLWidget / PaintGL scenario where you can afford to setup the global OpenGL state once and for all and simply call the rendering primitives each frame, you will have to restore pretty much everything just after the call to beginNativePainting (link/bind your shaders, set global parameters, select and enable various buffers, etc).
It also means that you should use native painting sparringly. Having each single widget do custom painting might soon bring your rendering to its knees.

Are Singletons EVIL in GUI Programming with Qt?

I'm just starting my first fairly large Qt project which will be mostly a bunch of screens with buttons, tab widgets, and Qwt Plots. The panel stack pattern described in Qt Quarterly 27 seems pretty nice for my application. Each of my screens is a QWidget encapsulated in a Panel which is shown/hidden by a QStackedWidget. However it uses a singleton pattern for each Panel so that they aren't all created immediately as the app starts and so that more than one of each screen isn't ever created.
So I started coding. Got the panel stack working. Added some code so that dynamically updating widgets aren't dynamically updating all the time. Got my history stack/back button working for the panels. Everything seems just fine, but I've got one nagging worry:
My code smells.
I am in no place to argue with any of the hate posted here and on blogs about the singleton pattern. I think I get it and the code I've written does make me feel a bit dirty with all the boilerplate lines and global objects. But I do like not having to worry about whether or not I already instantiated a screen before switching to it and adding it to my history stack. I just say switch to that screen, it's added to my history stack, and the magic works.
From what I've read there are also some cases where singletons can be worthwhile. Is this one of those special cases? The magic screen switching / history stack makes me think 'yes' but the sheer number of different singleton classes I'm going to have to create makes me think 'NO no NO NO NO'.
I want to just man up and figure out how to get the singleton pattern out of my code now so that I don't have to do it later. But I don't want to get rid of all my singleton classes just to get rid of my singleton classes because they're EVIL [citation needed].
Any input is much appreciated!
I don't really hate singletons, but this sounds like a case with no use for them. I don't understand why there are so many singletons in that article.
First, the PanelStack is a singleton by itself. Why? If that's your main widget, then just create it on the stack in the main(), which is both cleaner and faster. If it is a part of a more complicated UI, then put it there as a member of that UI. A regular class is just fine here, making it singleton only limits its possible uses.
Then, each panel is also a singleton? At this point even singleton lovers should begin to feel that there are too many of them already. Which is probably why you are asking this question in the first place. Let's see what real advantages singletons give here. Well, about the only advantage I can figure out from that article is the ability of lazily creating panels on the fly as they are needed. This is actually a good thing, but in fact, lazy creation and singletons are different patterns, although one often uses the other.
Why not just put all those panels in some common container instead? In this case, the PanelStack looks like a perfect candidate for it. It is the very place where panels are stored after all. Instead of a bunch of singletons, let's create a bunch of methods in the PanelStack:
class PanelStack : public QWidget
{
Q_OBJECT
public:
int addPanel(AbstractPanel *);
void showPanel(int);
RecordingsPanel *getRecordingsPanel();
ReecrdingDetailsPanel *getRecordingDetailsPanel();
private:
...
};
And so on. These get*Panel() methods can still create panels lazily as needed. Now, it's essentially the same thing as having a bunch of singletons, with some advantages added:
If we make panels children of the stack, they are automatically deleted when the stack is deleted. No need to worry about memory management which is always a pain with singletons.
You could even implement some sort of "garbage collector" in the PanelStack that deletes panels that haven't been used for some time. Or when some sort of "max active panels" limit is reached.
Now, the only disadvantage I can think of is that we have a dependency between the stack and the panels now. But what's worse, to store instances in one class, introducing a dependency, or to store them globally? If you think that the stack should be independent from panels, which does sound reasonable, then we probably just need another class to put all those things in. It could be a subclass of QApplication, or just some random "UI manager" class, but it is still better to store everything in one place than to store everything globally.
Using singletons here only breaks encapsulation and limits the possible uses of the whole UI. What if we want to have two windows with those panels? Or multiple tabs (think web browser)? Singletons will bite hard. And they are only really useful when the instance is accessed widely across many unrelated classes (think DB connections, loggers, pools and other typical singleton uses). They are mostly useless in an UI because with UI it is almost always obvious that "this thing belongs there, and probably nowhere else".

QAbstractItemModel.parent(), why?

I'm a (Py)Qt newbie, porting C# GUI code to Qt for a couple of days now. One question that I keep asking myself is why are QAbstractItemModel subclasses required to supply a parent() method, and why are they required to supply, in the resulting QModelIndex, the row of a child in the parent?
This requirement forces me to add another layer over my tree data (because I don't want to call indexOf(item) in parent(), it wouldn't be very efficient) that remembers row indexes.
I ask this because it's the first time I see a model based view require this. For example, NSOutlineViewDataSource in Cocoa doesn't require this.
Trolltech devs are smart people, so I'm sure there's a good reason for this, I just want to know what reason.
The quick answer is, "they thought it best at the time." The Qt developers are people just like you and me -- they aren't perfect and they do make mistakes. They have learned from that experience and the result is in the works in the form of Itemviews-NG.
In their own words from the link above:
Let’s just say that there is room for improvement, lots of room!
By providing a parent that contains a row and column index, they provide one possible way to implement trees and support navigation. They could just as easily have used a more obvious graph implementation.
The requirement is primarily to support trees. I couldn't tell you the reason, since I'm not a Qt dev... I only use the stuff. However, if you aren't doing trees, you could probably use one of the more-tuned model classes and not have to deal with the overhead of supplying a parent. I believe that both QAbstractListModel and QAbstractTableModel handle the parent portion themselves, leaving you free to just worry about the data you want.
For trees, I suspect that one of the reasons they need the parent is that they try to keep to only asking for the information they need to draw. Without knowing all of the items in a tree (if it wasn't expanded, for example), it becomes much harder to provide an absolute position of a given item in a tree.
As for the quandry of using indexOf(item) in the parent function, have you considered using QModelIndex's internalId or internalPointer? I'm assuming they are available in PyQt... they can be used by your model to track things about the index. You might be able to use that to shortcut the effort of finding the parent's index.

Resources