How-To: Use Qt custom slots & generate Mocs in Visual Studio 2010

A while back I had a play with Qt in Linux and wrote-up how to auto-generate MOCs with a bash script… This time I needed to get Qt working in Visual Studio 2010, on machines which get wiped every time they boot, so I needed a standalone “base-project” with minimal installation requirements for students to work from. So I made one…

Simple Qt Text Editor screenshot

Project Properties

Linked below is a Visual Studio 2010 project which is an incredibly bare-bones text editor in Qt. You can enter text, you can save it (to a fixed filename), and you can quit! That’s it!

But the project does have some redeeming features in that:

  • It’s completely standalone, because it comes with the required Qt headers, libs and dlls to do its thing, and
  • It has a batch file that runs as a pre-build step which auto-generates the MOC files (using an included copy of moc.exe) – meaning you can change any headers in the same location as the main source and it’ll update the MOC(s) for you on build without having to dip into the commandline.

Download: 1-Standalone-Qt-Project.zip

Please note, this download is for Windows 7 64-bit, and it includes the libs/headers/dlls/moc.exe from Qt 4.8.0 (the most recent at time of writing).

If you just want the batch file to autogen the MOCs for you, then the script itself is simply:

Place the batch file in the same location as your code, which is generally in the named project folder – so if I had a project called 2-QtTest, my code (and the batch file, and moc.exe) would live in 2-QtTest\2-QtTest. Finally, add executing the batch file as pre-build step like this (or just grab my project and use it as a base):

Visual Studio Qt Moc Prebuild-step settings

Additional

  • If you want a ton of Qt functionality you might need to copy more of the Qt headers into the include folder in the project (if you have the QtSDK installed, you can find these in C:\QtSDK\Desktop\Qt\4.8.0\msvc2010\include). I only put the QtCore and QtGui folders in to keep the project size down.

  • If you get a warning about being unable to delete a temporary file during build (generated by the genQtMoc batch file) – it could well be caused by AVG. For example:

    I’ve seen the error once or twice during build, but it’s not consistent – really, it’s just a tempfile being locked – shouldn’t be a concern. AVG finger-pointing source: karmiistha.

Source code after the jump for those who want it…

Main.cpp

Notepad.h

Notepad.cpp

Leave a Reply

Your email address will not be published.