How to Add QT Support to an Existing Visual Studio Project

QT is a cool GUI framework and the Visual Studio add-in is pretty neat… it allows you to code and deploy C++/QT apps without having to deal with QT’s include directories, linker dependencies, environment variables and all that jazz. You simply create a new QT project (an application or library) in Visual Studio just as you would for any regular VC++ project, select the modules you want to use, and thunderbirds are go!

But annoyingly enough, the add-in doesn’t allow you to take an existing vanilla Visual Studio project and turn it into a QT enabled project. Sure you could forget about it and manually do everything the add-in does for you. Or you could create a fresh QT project and migrate your source and settings to it, but that’s a royal pain if your project is complex. Since I’ve seen a few people asking about this missing feature and it’s bothered me in the past, I thought I’d post the solution I figured out (only tested on VS2008)… it’s actually very simple and it doesn’t even involve any assembly level hacking 😉

  1. Open your .vcproj file in your favourite text editor – if you’ve never seen one of these in the wild, it may surprise you to know that it’s plain XML… that’s what allows SVN to merge project changes without disaster.
  2. Change the Keyword part near the top to Keyword=”Qt4VSv1.0″ and adjust for your desired version.
  3. Add this to the globals section:
    <Global Name="lupdateOnBuild" Value="0"/>
    <Global Name="MocDir" Value=".GeneratedFiles$(ConfigurationName)"/>
    <Global Name="MocOptions" Value=""/>
    <Global Name="QtVersion Win32" Value="$(DefaultQtVersion)"/>
    <Global Name="RccDir" Value=".GeneratedFiles"/>
    <Global Name="UicDir" Value=".GeneratedFiles"/>
  4. For each build configuration (i.e. Debug and Release):
    • Add AdditionalIncludeDirectories=”$(QTDIR)include” to the VCCLCompilerTool entry
    • Add AdditionalLibraryDirectories=”$(QTDIR)lib” to the VCLinkerTool entry
  5. It should build now… open the QT settings for the project, select the modules you want (probably Core and GUI at a minimum) and you’re done.

Next step??? Someone write a script to automate this!

Posted in C++ | Tagged , , , , , , , | 6 Comments

10 User Interface Annoyances to Make the Blood Boil

I’ve been wanting to write about this topic for a while now, and in stark contrast to everything else I’ve written, this applies to everyone who has ever used a computer.  You don’t need to study HCI or programming to formulate your own UI-related ideas and pet hates. These are mine:

10.) Bad Search Functions:

There’s a simple rule here – if Google can search your website more adeptly than your search function can, you’re doing something wrong. If your search functions returns a million results and provides no way of narrowing down the results, you’re doing something wrong. If your search function is so painful that every search realistically requires several subsequent refinements with 30 second delays in between them, you’re probably pissing off your users. And this isn’t net specific either. Let’s face it; Windows search was pretty crap before 7.

9.) Bad CAPTCHAs:

I’m certain you know what a captcha is – it’s a Completely Automated Public Turing test to tell Computers and Humans Apart! Still don’t know? How about “notoriously annoying distorted image which supposedly contains legible characters, rears its ugly head whenever you try to register on a website and is apparently a good test of whether you’re a human or robot”? Yeah, now you’re with me. In all fairness, not all CAPTCHAS are bad and I think Google does a rather good job with their ones. But it’s hard not to hate them when you encounter monstrosities like this:

I discovered it while trying to register on a well-known NZ site… it was lurking in the wild without a refresh function or audio aid. And to top it all off, it came with this message “If you are visually impaired or cannot otherwise read this code please contact the Board Administrator.” Really?!? I don’t think I need to be visually impaired to struggle with that one. Still, at least the reCAPTCHA folks are making the most of them.

8.) Deceptive Progress Bars:

Most people consider progress bars to be a farce, and it’s no surprise when they do wacky things such as jumping from 10% to 90%, going backwards, restarting an unspecified number of times, and generally being inconsistent.

Yes, there’s a plethora of challenges involved in developing a good progress bar (whether time or percentage based), but it’s not rocket science… try to do something so that your progress bar at least roughly reflects real progress. If you can’t programmatically estimate how much time will be required for chunks of program execution, perhaps a heuristic estimate based on test results would be more appropriate? Or perhaps a progress bar really isn’t required in the first place, when the user simply desires assurance that there’s at least something going on and that your app hasn’t crashed?

7.) Give Control to the User:

No-one likes waiting and a user should be dictating their computer’s operation rather than the reverse. This implies that users should have some degree of control over time-consuming processes – after all, it’s their time which is being sucked away. I’m baffled as to why Microsoft hasn’t added Pause/Resume functionality to file copy operations when it’s so obviously in massive demand. And unskippable cinematic sequences in games are definitely a no-no along with annoying splash screens.

But I feel the worst offender is iTunes. Adding music to your iPod entails a considerable number of processes – songs must be added to your iTunes library, converted if necessary and synced to your iPod. Then album art must be obtained and gapless playback information calculated. This is all quite hard drive intensive, which may be fine for power desktop systems but absolutely cripples my single drive laptop. Surely iTunes could provide a less intensive “Don’t ravage my computer as I’d like to be able to do other stuff at the same time” mode? Basically a background version of syncing?

6.) Windows which Should Be Resizeable but Aren’t:

I have a 24″ widescreen monitor. The variable value there is 389 characters long. Only 42 characters are displayed as the textbox is inside a non-resizeable window. Enough said.

Posted in User Interfaces | Tagged , , , , , , , | 2 Comments

Adventures with Templates – Basic C++ Type Introspection without RTTI

Template Metaprogramming

C++ works in weird and wonderful ways, and there is undoubtedly some level of mysticism surrounding anything involving templates. Templating was initially introduced to C++ as a means of writing generic statically typed containers without using macros, and in general, to reduce the amount of code required to perform tasks. But it wasn’t long before its power was harnessed for metaprogramming purposes (by accident), allowing for chunks of code to be evaluated at compile time rather than runtime. I doubt that even devout fans of C++ would deny that its syntax can be downright ugly and bewildering at times, but its beauty is in the sheer power and control it gives the programmer. Part of the C++ philosophy is that the programmer is not restricted to what the language designers had in mind… and there are many innovative design patterns and idioms (examples) resulting from programmers twisting C++ in ways which could never have been imagined by its designers.

Basic ‘Reflection’ without RTTI

A major drawback of C++ is its lack of full runtime reflection. The closest inbuilt feature we have is typeid, the minimal type identification mechanism supported in RTTI (Run-Time Type Information) mode. Unfortunately, its behaviour is undefined and the type_info object it returns is compiler-specific. So typeid(int).name() could return “class int”, it could return “i”, or even “cellar door” if a compiler writer should be in a whimsical mood. Furthermore, the mere thought of the overhead incurred by RTTI is enough to make embedded devs shriek in the night.

Type traits are often used to accomplish tasks for which reflection is usually used in other languages, and a common non-RTTI solution for type comparisons is given below. int and char are considered the same if is_same<int,char>::result == true. In the general case, result is statically initialised to false but the compiler chooses the template specialisation (which initialises result to true) when T is equal to U. Note that this of course will not work for polymorphic types.

template<typename T, typename U>
struct is_same       { static bool const result = false; };

template<typename T>
struct is_same<T, T> { static bool const result = true;  };

SFINAE (Substitution Failure is not an Error)

In the last month or so, I’ve become more interested in template hax and the concept of SFINAE intrigued me. As this article explains, SFINAE revolves around the idea that in some situations, an invalid substitution of template parameters will not result in a compiler error. One of these situations is function overload resolution, as demonstrated in the below example from that article. An f<Test>(10) invocation would be delegated to #1 as Test encapsulates a NestedType typedef alias, and so the substitution is valid. When matching an f<int>(10) invocation, the compiler would silently remove #1 from the set of candidate overloads as int::NestedType is invalid, and finally delegate to #2.

struct Test { typedef int NestedType; };

template<typename T>
void f(typename T::NestedType) {}        // Definition #1

template<typename T>
void f(T) {}                             // Definition #2

Basic ‘Reflection’ using SFINAE

After seeing SFINAE solutions posted here for determining whether a type governs a function, I decided to experiment with it and roll my own SFINAE type comparison for the hell of it (and to learn something along the way). Note that this solution is far inferior to the standard non-RTTI one for reasons outlined below, but I thought I’d post it anyway as it’s an interesting specimen of code.

template<class S, class T>
struct SameClass
    template<class Identical, Identical>
    struct type_match;                    

    template<class _1>
    static char (& func(
         type_match< T& (_1::*)(const _1&), &_1::operator => *) )[1];

    template<class >
    static char (& func(...))[2];

    static bool const value = sizeof(func<S>(0)) == 1;

template<class c1, class c2>
bool IsSameClassAs() { return SameClass<c1,c2>::value == 1; }

func is a templated function with two overloads. The first definition takes a pointer to a type_match struct and returns a char[1] array by reference (for which sizeof is 1). The second takes any parameter(s) and returns a char[2] array by reference. SameClass<S,T>::value will equal 1 if func<S>(0) delegates to the first overload. This can only happen if both of the type_match template arguments can be successfully substituted as IDENTICAL (implying they must be equivalent). If they cannot, the compiler will silently delegate to the second overload in SFINAE fashion. The first argument is a member function pointer to a method in S which takes a const S& parameter and returns T&. The second is a member function pointer to an operator= method defined in S.

Essentially, for the first overload to be chosen (and S and T to be considered equal), S must have an operator= method defined which takes const S& and returns T&. If S and T are indeed the same types, S is guaranteed to have a copy assignment operator which satisfies this criteria (whether it is explicitly implemented or not). However, a false positive will result if S offers an op= method which returns T& – I’m not sure why anyone would implement such a method, but it is permitted by MSVC. Furthermore, this implementation will not work for primitive types or pointer types as the scope operator is applicable to neither. I must reiterate that this is not a sensible solution for reflection when there are far simpler and more robust solutions available. But interesting nonetheless.

Posted in C++ | Tagged , , , , , , | 4 Comments

C++ GUI Libraries, QT and the Signals/Slots Paradigm

It’s a while since I last posted anything as I’ve been tied up with uni work (and I should really be doing a 3000-4000 word report now, but I’m hoping it’ll write itself). I was planning to blog about something a little more general, perhaps related to user interfaces, but for now you’ll have to deal with an esoteric and mercilessly long post. Skip the rambling about our project and migration to QT if you want – the second half about Signals/Slots is the (more) interesting part 😀

I’m working with a fellow classmate at uni on a year long project centered around algorithm visualisation which I may blog about in the future. Up until recently, we’d been using OpenGL for graphics and SFML for basic windowing and events. We required some scrollbar, menu and button functionality, so short of writing widgets ourselves, we opted to go for a GUI library. Now before that, I’d never developed a GUI in C++, and for good reason. Having been spoiled by the well documented and designed Swing, the rapid prototyping of TCL/TK, and the superlative .NET WinForms/WPF, most C++ GUI code strikes me as being a little close to the metal when I want to whip up a quick interface (*cough* Win32 *cough* MFC). On the other hand, based on my experiences with TCL/TK, prototyping is quite rapid until you want to do something the library designer never thought of, and you spend hours tearing your hair out trying to figure out how. C++ GUI libs are arguably less likely to suffer from this problem. Incidentally, I am learning a bit of WTL for developing a Foobar plugin as a personal project.

Migration from OpenGL/SFML to QT

A bit of preliminary research into GUI libraries led us to this, a seemingly promising way to quickly integrate our SFML code into QT widgets. However, that solution was short-lived as we soon discovered that the WA_PaintOnScreen attribute used to inform QT that we want to take care of the widget drawing, is not a cross-platform feature. After some deliberation, we decided that we didn’t really need OpenGL/SFML for now and that our project should undergo a full migration to QT… painting would be performed by the QPainter class but there is also a QGLWidget class available, should we require it. The migration was time-consuming but smooth for the most part. The main obstacle was finding an easy way to allow a QWidget to draw on top of its child widgets, a requirement for our graphical model. In Swing, one can simply override paint() with a version which calls paintChildren() before paintComponent() (and throw paintBorder() in the mix somewhere). We employed the quick hacky solution of delegating the parent drawing to a child widget with a different z-order to its sibling widgets. If anyone knows of a better solution, please let me know 🙂

QT and Signals/Slots

On the whole, QT is an excellent framework. It is well-designed and documented, portable, performant, versatile and it offers a wide range of features. Not to mention, it introduced the innovative signals and slots paradigm as an implementation of the Observer pattern. Whereas many languages use callbacks and .NET uses events/delegates (not so different), QT uses the signals/slots mechanism – and you know it must be good if it inspired the Boost devs to create their own version. The basis of signals/slots is that widgets (or other entities) declare a signal for each type of event they can raise, and various slots as event-handlers. Communication between objects is easily accomplished by connecting signals and slots together. As an example, our AwesomeWidget is updated periodically by simply encapsulating a QTimer and, during construction, wiring its timeout() signal to a slot method in the AwesomeWidget class like so:

class AwesomeWidget : public QWidget
          connect(&timer, SIGNAL(timeout()), this, SLOT(updateMe())); 
          // set interval, start timer etc...
     QTimer timer;
private slots:
     void updateMe();

Pretty simple, huh? The QTimer class similarly includes the Q_OBJECT macro and declares a timeout() signal with the same signature as updateMe(), which is fired by calling “emit timeout();”. Note:

  • The lack of boilerplate bloat, Observable/Observer coupling or intermediate Event/Action classes.
  • Despite the fact that the updateMe() slot is declared with a private access modifier, it can actually be connected to any signal with a consistent signature, regardless of location. This yields the advantage that updateMe() cannot be inadvertently invoked by code outside the AwesomeWidget class.
  • The cardinality constraint between signals and slots is many-to-many, and signals can in fact be triggered by other signals.
  • QT’s signal/slots implementation can be threadsafe, provided you follow a few basic rules. How a signal emission operates depends on the optional arguments passed to connect(). Emit calls can operate synchronously and execute signals on the same thread, returning once they complete. Or they can have signals executed on the receiver’s event-thread, in either a blocking or non-blocking fashion.

The only drawback (and it’s a pretty small one really), is that this code must be passed through QT’s meta-object compiler which interprets and verifies the signal/slot annotations, and generates the required runtime reflection code. I use a QT MSVC plugin which handles that part of it anyway.

And that’s me for another undefined stretch of time. Happy coding 🙂

Posted in C++ | Tagged , , , , , , , , , | Leave a comment

C/C++ Assertions and Defining Your Own Assert Macro

Why should I use assert???

The assert macro defined in <assert.h> is a C programmer’s best friend. Really. With the plethora of potential pitfalls in the wild world of C, assert presents a simple and lightweight way of assuring that various conditions in your program hold true so that you can develop in a defensive manner – after all, we’re taking nothing for granted and taking no prisoners 😉

Runtime assertions should be used judiciously. They establish conditions which absolutely must be true, because if they aren’t true, then there’s something seriously wrong with the logic of your program (read: you botched something somewhere). Consequently they work quite nicely for verifying function/method pre-conditions during development. Assertions are NOT intended for dealing with user/system errors such as invalid input, failure to open a file or a loss in internet connectivity.

Another great thing about asserts is that they can be compiled out of code simply by defining NDEBUG. That can also result in some very nasty surprises if any of the code you’re asserting causes side-effects. Imagine a scenario where you’re developing in debug mode and you have some code like this – AttachParachute() of course returns a boolean value.


To your delight, after typing your last line of code, you feed it to your machine, and everything is hunky dory and no-one dies. Later on, you attempt a release build only to find that your skydiver remains at terminal velocity for a little longer than expected. After the lugubrious feelings subside, you’re left wondering why fate has it in for you. “But my code ran perfectly before! And none of my assertions are failing!” It’s crucial to understand that many release builds define NDEBUG which means that assert statements and anything inside them will not exist in the binary… your skydiver never had his parachute attached! Moral of the story is, assert results of operations, not operations themselves.

All the cool kids have their own assert macros… I want one too!!!

Ok, so maybe my definition of ‘cool’ is completely skewed here, but that’s quite beside the point… Regular C assert is just fine and dandy but there are many possible reasons for wanting to write a custom macro. Maybe you want to log failed assertions in a project specific manner rather than simply printing to stderr? Maybe you’re working in an embedded environment and stderr isn’t available (and you’d rather emit the assertion details in morse code blips)? Maybe you want to support custom handlers since your unit-testing framework doesn’t handle failed asserts gracefully?

The reason I initially defined my own assert macro is rather foolish in retrospect. I was working on a static library and a DLL, as well as a console app which uses both of them. I noticed some strange behaviour with regards to how my asserts were reporting file/line data – all of the failed assertions were correctly halting execution and spawning dialogs but only sometimes was the assertion location data being reported in that dialog. Had it not been for the reams of console output, I probably would have noticed that the assertion data was being printed to the console in the cases when it wasn’t being sent to the dialog. But that moment of enlightenment came only after I’d already hacked together a quick assert macro. As it turns out, how assertion data is reported in MSVC depends on the app type as explained here. Both console apps and Windows apps spawn dialogs, console apps report only to stderr, Windows apps report only to their dialogs.

Sample C++ Assert Macro

#ifndef NDEBUG
  #include <cassert>
  #define UL_ASSERT(condition)
          std::cerr << "Assertion failed at " << __FILE__ << ":" << __LINE__;
          std::cerr << " inside " << __FUNCTION__ << std::endl;
          std::cerr << "Condition: " << #condition;
  #define UL_ASSERT(condition) (condition)

Here is a skeleton C++ assert macro which isn’t too different to the one I originally wrote. There are several points to note:

  • Failed assertion data is always printed only to stderr/cerr (but a dialog box will still be spawned regardless of app type… at least in MSVC).
  • If NDEBUG is defined, rather than effectively compiling out UL_ASSERTs (as happens with regular C asserts), a different version is used instead; one which simply evaluates the condition and doesn’t verify it. This protects against the code-with-side-effects problem I mentioned above. And you needn’t worry about unnecessary condition evaluations resulting in code bloat or a performance hit provided that your compiler is smart enough to optimise out simple conditions which don’t affect dataflow (most compilers are).
  • The macro contents are contained within an extra pair of braces to ensure that the IF clause contained within a macro expansion cannot conflict with a subsequent ELSE clause.
  • The condition is enclosed in parentheses in accordance with good macro practices (no, that’s not an oxymoron ;)) to ensure that an assertion like UL_ASSERT(2 < 0) expands to if(!(2 < 0))… rather than the erroneous if (!2 < 0)… which yields entirely different results.

And that about wraps up this post. I hope someone finds it useful. Feel free to reuse and modify the skeleton assert for your own purposes. And feel free to point out any mistakes I may or may not have made 😛

Posted in C, C++ | Tagged , , , , , , , , | 1 Comment

Hello universe!

WordPress kindly created a blog intro for me entitled “Hello world!” but in an attempt to distance myself from that coding cliché and Earth in general, I thought I’d instead greet the universe. So hello, this is my entry into the inter-galactic blogosphere!

Pretentious blather aside, here’s a bit about me. I’m 22 and in my fourth and final year of studying for a BE in software engineering at the University of Auckland (that’s in New Zealand for you international folks). Over the past two summers, I’ve worked for a medical software company and a robotics automation company, and enjoyed my time at both immensely, notwithstanding the delightful deadlines we all love.

I’ve fiddled with computers for as long as I can remember (since the age of 3) and I discovered programming in high school through the lunchtime QBasic club which, I’ll add, means I’m “mentally mutilated beyond hope of regeneration” according to Dijkstra. I did the normal nerdy QB things and wrote a BEDMAS calculator, a maze solver, a starfield simulator, 2D tile mapped games etc. I also learned a bit of VB before programming went off my RADAR for a few years until I picked it up again in university.

My software-related interests lie in operating systems, design, computer graphics and maths/algorithmics. While my courses have focussed on teaching using Java, my language of choice has become C++ in the last 6 months, although I’m fond of C# .NET and I’ve been dabbling in a bit of Python as of late. Beyond that I’m utterly obsessed with music (I mod on MusicBanter) and I also enjoy British sitcoms, gaming, and reading.

So what is the purpose of this blog’s existence? Part of it is motivated by the selfish desire to aggregate my thoughts and document my journeys in software development. Part of it is inspired by the collective knowledge of the members of Stack Overflow, which is an amazing resource. And part of it is the direct result of my experiences of reading useful tutorials and finding tech solutions written by normal everyday people in their blogs. In the same way, I hope that someone will find what I post here useful, or at least mildly interesting.

And as for the name, it’s the software version of the human condition!

Posted in General | Tagged , , , , , , , , , , | Leave a comment