In c++ when u allocate memory, u should always delete them (in Destructors for example). But in qt u often don't worry about deleting objects. Qt does it for u. IDE does not correctly show all the memory leaks. I saw code somewhere like this:
anyLayout->addWidget(new QLabel(QString("text")));
will this QLabel be truly memory leak?
The same question about adding the same way QListString to QComboBox.
No, QWidgets added to a layout will be automatically parented to the layout. This is explained here.
Note: The ownership of item is transferred to the layout, and it's the layout's responsibility to delete it.
When the parents are cleaned up, so will the children. I would encourage you to read about Object Trees & Ownership in Qt.
Related
In my application ( QML, QtQuck 1.1, C++ ) I want to reuse some items in my screen.
Generally there are two options ( please let me know if there are more)
1.Use a separate .qml file and put the basic block inside and import in new screen
2.Create a component and use loader to load it.
But I cannot understand which option to use.
Whats the difference between these two options.
Or
which will consume less CPU load?
Thanks!!
Use the first approach unless:
You need to conditionally load QML based on some runtime condition. Note that file selectors are more efficient than Loaders for this purpose, but it might not be possible to use them, depending on your requirements.
You want to avoid loading expensive QML until absolutely necessary (lazy loading).
You should especially be wary of using Loader to load components that are created in large numbers (such as those used as delegates in views), as it doesn't come for free.
To clarify on a part of the answer provided by Mitch:
You should especially be wary of using Loader to load components that
are created in large numbers (such as those used as delegates in
views), as it doesn't come for free.
Using a Loaderas a delegate just to create some other object doesn't make sense except for a very narrow case. You can directly and most definitely should use YourItem {} as a delegate instead. Delaying instantiation in a view delegate in particular is not a very good idea, since that will mess up the view layout, absent the actual item's dimensions which can't be determined without loading it. Even in the case where the Loader is not the top element but nested, it won't be problematic, as QML views only instantiate delegate objects for objects that are in view, if your model has 10k objects it is not like you will have 10k loaders unless they are all in view, which ... won't me much of a view.
Also, if you really need dynamic instantiation, then you will need at least an Item to use as a parent anyway, so the overhead of the Loader becomes negligible and a very good trade-off for the extra flexibility and functionality such as use bindings for the item or to set a dynamic source component. You could do that with an Item but you will have to implement it yourself, and in the end it will end up with larger overhead than Loader.
The CPU time for either of the approaches will not make a difference. Now if you are dynamically creating lots of objects manually, you definitely neither need nor should be using loaders. And not because of the CPU time, but because of memory usage - QML objects are memory hogs, a few thousand objects of medium complexity will likely run you into serious trouble on a 32bit build, especially on a mobile device. Even an empty, non visible QtObject is like 160 bytes. On top of that JS garbage collection is pretty much a joke when it comes to releasing resources, it will do fine on reusing. If you for example create 1 GB of visual items, then delete them and force garbage collection, you will only get a tiny fraction of that memory back, but if you create the objects again, memory usage will be pretty much the same +/- a few megabytes.
In short, in separate .qml file put global component wich you will include and use in different files.
Create component in same file if you will use it only in one file.
Also it depends on the size and complexity of the component. Big and complex component preferably place to separate file.
Compiling faster when all code in one file, but development faster when everything in their place.
I'm pretty new to QT's graphic view frame, and I couldn't find anything about this in the docs or on Google.
I have a GUI application that draws a representation for some data. The application itself does some work with matrices / vectors (a neural net thing) and has to represent it on a QGraphicsScene. So far so good, but I've noticed that the app segfaults & crashes sooner or later (and usually sooner) if I try to update the QGraphicsScene from another thread. The QT Docs say nothing about thread-safety & Google gives nothing. What I want (and pretty much need) to do is run the calculations & update the GUI representation accordingly, but the GUI controls etc themself have to remain responsive. As I said, my first thought was to do the whole thing in another thread, but it crashes randomly if I try to.
Is there any "accepted practice" to do this kind of thing in QT or is there some gotcha that I don't know of in the graphics view framework itself?
The Qt docs actually say quite a lot about thread safety. If the docs for QGraphicsScene don't say anything it's because they are not thread-safe, consistent with the behaviour you are seeing.
What you need to do is run your calculations in another thread and synchronise that thread with the main GUI thread as appropriate. A simple way to do this would be to set a flag in the main thread when the calculations are ready for display. That way you can call the appropriate QGraphicsScene methods in the main thread at the right time by simply checking the flag.
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.
Coming from the Symbian world, I'm used to using the heap as much as possible to avoid running out of stack space, especially when handling descriptors. CBase derived classes were always dynamically allocated on the heap, since if they were not, their member variables would stay uninitialized. Does the same convention apply to QObject-derived classes?
In Qt it seems to be common to put, for example QString, on the stack. Are the string contents put on the heap while QString acts as a container on the stack, or is everything put on the stack?
As sje397 said: It's idiomatic to put QString and containers on the stack, as they are implicitly shared. Their internals (pimpl idiom "d" pointer) are created on the heap. There is no point in creating the object itself on the heap, too. Just causes memory-management hassles and you lose the intended copy-on-write properties when passing pointers to strings/containers around.
QObjects on the other hand you want to create on the heap in almost all cases, as otherwise they would be destructed again right away. They can't be copied or assigned (well, one can enforce it for own subclasses, but the QObject semantics are broken then), and usually they are supposed to survive the method body they are created in.
Exception is QDialog, which is often created on the stack, followed by QDialog::exec, which blocks until the dialog is closed. But even that is strictly spoken unsafe, as external events (RPC calls, background operations) could cause the dialog to be deleted by its parent (if the parent itself is deleted) before exec returns.
Then having the dialog created on the stack will cause double deletion when unwinding the stack -> crash.
QString, and many other Qt classes, use implicit data sharing. That implies that memory is generally allocated on the heap.
i have some clarification regarding Qt programming.
In Qt most of the time we instantiate widget by allocating the memory dynamically.
is there any advantages of doing like this from Qt prospective? and what about de-allocation of memory for the widget?. do we need to manually call delete for the allocated memory or Qt handles?
Example
QListView *newlist = new QListView(); //This is good? if so why?
QListView newlist; // why not this?
Looks like it's safe to do stack allocation. See this answer. In the case of Symbian, it might differ, though. This question brings up some good points.
I think with Symbian, you have a limited stack space, and many of the objects themselves use data sharing which is allocated on the heap anyway. In that regard, it might be a good idea to keep doing it dynamically.
QListView* newlist = new QListView(); //This is good? if so why?
Only if you store the newlist pointer somewhere and delete it manually later.
If possible, I would suggest allocating you widgets on the stack. This is not possible, however, when using the technique I'm about to explain.
When designing complex widgets you would normally create an object tree of widgets. Meaning that every widget, except for the root widget, has a parent. When a parent is deleted, it will automatically delete all its children. This method is very convenient because you will only need to keep track of the root widget.
In your case, you'd do something like this:
QListView* newlist = new QListView(parentWidget);
See my my reply about QObjects.
In short: One creates widgets on the heap, as they usually must survive the current method, and they cannot be assigned nor copied. QWidgets delete their children when they themselves are deleted (or more general, QObjects delete their children), so there is usually no memory management problem if you pass a parent to the widget.