So, last year I went to the Qt Developer conference here in S.F. It’s a great opportunity to meet up with Qt Developers from all over the world. One of the amazing things about Qt is how easy it is to get up and running and be productive; unfortunately, it’s easy to get stuck in a rut where you always do things the same way and don’t necessarily try new ways of doing the same things, or really look at performance in your code, and just generally be a fair-to-middling developer with Qt.
I attended a well-run session on Qt tips and tricks from the trenches, and ended up with two pages of longhand scrawl of good thoughts that I either hadn’t really explored in Qt, or realized I needed to learn more about. These got transcribed to a bullet list of items, some of which I’ve followed up on, and some I haven’t. Here are a few, with some of my observations about them, preserved for posterity and your use!
invokeMethod
for Deferred Method Invocation
You often want to run some bit of code just after a method call; deferred initialization is a common case, where your constructor does the bare minimum to set something up, and then once everything’s up and running you want to do a bit more initialization. A single-shot timer is a good way to do this; you can use QTimer::singleShot
with a short delay to trigger a slot in your class. You can also do the same thing using QMetaObject::invokeMethod
, passing Qt::QueuedConnection
as the connection type. When you do this, Qt sends a QEvent
and the method is invoked as soon as the application enters the main event loop, which is probably what you were trying to accomplish with the timer anyway.
Implementing <<
and >>
for QVariant
Serialization
This is a “well, duh” if you’ve read Qt’s serialization documentation, but you can implement <<
and >>
for your class using QDataStream
to support serialization.
I like to take the time and do a human-readable string for QDebug::operator<<
at the same time, too, so I can log complex data types to the debug console when doing printf-style debugging.
Use const
References with foreach
This should go without saying, but a lot of people forget. If you're iterating across a Qt collection using foreach
, don't forget you almost certainly want to use constant references to do so. Otherwise, the implementation makes a copy of each item being passed to you at the beginning of each pass through the loop, and destroys that instance at the end. All of this happens on the stack, of course, but you're still paying the constructor and destructor penalty, and if your object is large, you're thrashing your stack footprint needlessly.
I'll post a few more of these next week!