Slashdot Mirror


C++ GUI Programming with Qt 4

Ravi writes "When somebody talks about the Qt Framework, the first thing that comes to mind is KDE one of the most popular Desktops which is built using the Qt library. Qt is a C++ GUI framework created by the Norwegian firm Trolltech which can be used to build applications for a variety of OSes and platforms. The latest version of Qt (Ver 4.0) contains huge improvements over its earlier versions such as advanced modal/view functionality, easy to use template containers and better Unicode support just to name a few. I have been excited about the ease with which one can build GUI applications using Qt. Trolltech provides the library in two licences - the free licence which mandates that the applications developed be released under GPL and a commercial non-free licence which allows one to develop closed source applications using Qt." Read the rest of Ravi's review. C++ GUI Programming with Qt 4 author Jasmin Blanchette and Mark Summerfield pages 540 publisher Prentice Hall rating 9 reviewer Ravi ISBN 0-13-187249-4 summary A great book to learn the latest version of Qt (Ver 4.0) to create applications that run natively in Linux/Unix, Windows and Mac OS X

I found the latest book on Qt titled "C++ GUI Programming with Qt 4" authored by Jasmin Blanchette and Mark Summerfield and brought out by Prentice Hall to be a remarkable book in that it takes the readers through the basics of creating applications using the latest version of Qt and gradually shifts to explain the more advanced concepts of GUI programming using this C++ framework.

The book, all of 540 pages is divided into three parts - the first part containing 5 chapters dealing with Basic Qt, the second part titled Intermediate Qt which contains 11 chapters and the final part titled Advanced Qt containing an additional 5 chapters.

The major work in picking up skills in a new GUI framework revolves around getting to know all the classes and their member functions. And learning Qt is no different. In the first five chapters (Part I of the book), one gets to know the rudimentary concepts behind creating GUI applications using the Qt toolkit. And remarkably, instead of boring the readers with the different Qt classes, the authors take a hands on approach and introduce the concepts via examples.

In chapters 1 through 5, the readers are introduced to rapid dialog design using the Qt Designer, introduction to the main Qt classes such as QApplication, QObject, QWidget and its child classes as well as a good understanding of the concept of Signals and Slots which form the meat behind communication between different objects in Qt. Apart from that the 5th chapter also introduces to the reader the concept of Double buffering - one which is used popularly by the programmers in eliminating flicker in the GUI interface.

The sixth chapter titled "Layout Management" falls in the second part namely "Intermediate Qt". Here one gets to know and tryout the different layout classes that are available in Qt using which one can easily design sophisticated GUI applications. This chapter also gives the reader an introduction to Multiple Document Interface by way of an example.

Event Processing forms the basis of the seventh chapter where the authors explain how to catch events such as key presses and timers. Apart from that the authors also explain the five levels at which events can be processed and filtered in Qt.

Qt has an excellent collection of classes for creating 2D and 3D graphics. And from version 4, the classes are grouped into modules which need only be plugged in on a need to use basis. The primary class which deals with the 2D graphics engine in Qt is the QPainter class. The use of this class has been explained in detail in the eighth chapter titled "2D and 3D Graphics". Other than that, one also gets to know about the OpenGL module in Qt which makes it very easy to integrate OpenGL code into Qt applications as well as the classes which implement printing.

It is really interesting to see that the entire subject of Qt is apportioned into separate chapters with each chapter dealing with a particular topic. For example, if in the 9th chapter, the authors dwell on explaining the classes which implement drag and drop support, the succeeding chapter elaborates on the Model view controller architecture which forms the basis for most item view classes which implement tables, tree views and lists.

Another thing worth noting is that each chapter is explained with a complete stand alone example which makes it easy to try out what one has learned and also get a better idea of the concepts behind the classes that are explained. So while learning say about the container classes in Qt, the reader can actually try out an example and the code is accompanied by step-by-step explanations which makes it much more simpler to grasp the concepts.

All object oriented languages contain what are known as container classes - those which are responsible for creating sorted and unsorted data arrays, vectors and lists. And C++ has a couple of them in the Standard Template Library (STL). Qt has its own wide array of container classes which sport a number of improvements over STL in that they support implicit sharing (Copy on Write) which gives the applications a significant performance boost. In the 11th chapter titled Container Classes, the authors explain the concept of containers and the Qt classes that can be used for the same.

The next two chapters deal with writing and reading data from files as well as databases. And in each case, the concepts are explained with the aid of examples which makes the narration much more interesting to follow.

Qt has good support for Networking as well as XML which is evident from the 14th and 15th chapters which elaborate on the classes responsible for these. Even though these two short chapters do not cover all the networking or XMl concepts, I found them to impart a good idea of the use of a couple of important Qt classes related to networking and XML.

The 17th chapter titled "Internationalization" falls in the Advanced section of the book. I found this chapter to be an eye opener in that, with Qt's robust use of Unicode, it is possible to create applications which support a wide variety of non-english languages.

But one of the very important concept of multi-threading is explained in the next chapter titled what else "Multithreading" where the authors teach how to create threads easily in Qt.

If one looks at any KDE application, it will be evident how the parent application can be extended by use of plugins. A plugin is a dynamic library which implements a particular interface to provide extra functionality to the user. In the 19th chapter, one gets to know how to create dynamic libraries using Qt which can then be plugged into the parent application.

In the penultimate chapter, the authors explain all the platform specific features and tweaks such as using ActiveX in Windows and handling session management in X11. There are also four pages - which I believe to contain the shortest chapter I have ever come across and where a couple of classes which can be used in programming for embedded devices such as mobile phones are listed. By including this tiny chapter, perhaps, the authors were sending a signal to the developer community that Qt is fully ready for use in embedded development.

From start to finish, I found the book immensely enjoyable. The style of narration of the authors which interleaves the example code with the explanation is ideally suited to pick up skills in using any toolkit without getting bored, especially since the bulk of the learning involves acquiring a fine understanding of the classes the toolkit provides. As a bonus the book also provides an appendix which gives an introduction to C++ for programmers who use Java or C#.

The single CD accompanying the book contains Qt library in the source form for the Linux platform as well as for Windows and Mac platforms. I did not have any problems in compiling the source and installing the library in Linux using the instructions provided in the book. And within a little more than an hour (the time taken to compile the source code), I was able to start coding and compiling the examples given in the book. All in all, I find this book to be an invaluable guide in picking up skills in programming in the latest version of Qt (4.0).

Ravi Kumar likes to share his experiences in programming and in using Linux through his blog on Linux."

You can purchase C++ GUI Programming with Qt 4 from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

19 of 148 comments (clear)

  1. I am the very modal of a modern slashdot editor by edittard · · Score: 2, Funny
    advanced modal/view functionality
    That's a combination of model/view and modal dialog boxes, is it?
    --
    At the bottom of the /. main page it says 'Yesterday's News'. Well they got that right.
  2. Interoperability by lkeagle · · Score: 2, Insightful

    Does the book explain any methods for dealing with interoperation with other frameworks? Gnome, perhaps?

    I've always found that the most useful books are the ones that provide direction on how to get your application to work well with others...

    P.S. F.P.

  3. Update for 4.2? by Abby+The+Wonder+Dog · · Score: 2, Informative

    It is too bad that this book couldn't have been based on version 4.2 coming out soon. There are some major new features in the upcoming release, most importantly (IMHO), QGraphicsView, the new canvas. http://doc.trolltech.com/4.2/qt4-2-intro.html

    It also looks like they'll try to squeeze in some cool SVG related stuff. http://zrusin.blogspot.com/

    Man, Qt simply pwns GTK

  4. Re:gui and native code - bad combination by gatkinso · · Score: 2, Informative

    Well, when I write C++ code, I rarely use malloc().

    --
    I am very small, utmostly microscopic.
  5. Re:Platform license. by ardor · · Score: 4, Informative

    Sort of. The Windows version has the same license, but has no VisualC support - this is included in the commercial version only. The free one only supports MinGW.

    --
    This sig does not contain any SCO code.
  6. The free edition by ratta · · Score: 2, Insightful

    does not require the application to be GPL, it requires it be open source (OSI), since the free edition is dually licensed GPL/QPL. The funny thing is that if Qt were QPL only, you could use almost all opensource licenses (eg. BSD) but not GPL, because the GPL require anythings you link with to be GPL compatible as well! So dual licensing is really necessary :)

    --
    Wondering why i am doing so strange posts? I am trying to get a "+5,Flamebait" or "-1,Insightful" rating.
  7. Re:gui and native code - bad combination by ardor · · Score: 2, Insightful

    Indeed, GUI development is one of the areas where managed environments shine. However, it IS possible to deal with this in C++. I agree that if I want to put a label in a window, I dont want to have to handle its deallocation, i.e. I want a "fire-and-forget" feature. I accomplished this in my wrapper by letting the parent deal with its children. It is a very simple concept, but works very well. I can write "new Label(mainwindow,"Here is my label",22,11);" and do not ever have to worry about a delete call or about memory leaks.

    IMO the best thing is to make the GUI purely data-driven, however. Stuff the entire layout in a XML, and the application only has to connect its event handlers to the named signals (assuming a signals-based event dispatching mechanism). AFAIK libglade does it like this. The huge advantage is that redesigning the interface no longer requires code modification. Don't like the button position? Move it down, you dont even have to recompile.

    --
    This sig does not contain any SCO code.
  8. How to get Qt to work with Visual C++ by everphilski · · Score: 2, Informative

    It is possible ... and not too difficult instructions here

  9. Design flaws in QT? by Anonymous Coward · · Score: 4, Insightful
    Has anyone using the QT API noticed that its behavior when it encounters an error isn't well-defined or easily detectable by the user of the library? For instance, look at QFileInfo's size member function.

    Returns the file size in bytes, or 0 if the file does not exist or if the size is 0 or if the size cannot be fetched.


    So, if it returns a zero, that could mean that there is a problem that your application may need to do something about or report, or the file does not exist, or the file exists but is zero bytes. How incredibly uninformative. But at least that member function documents its behavior it something bad happens. As I glanced through the other member functions, it became apparent that most of them do not bother to say what happens when the shit hits the fan. No return codes, no exceptions, no nothing.

    Sadly, many of the classes in the library are like this. Sure, I could write an application using QT, but I wouldn't know how to handle failures simply because QT doesn't document the behavior in those cases. This is surprising, considering that QT is considered a quality library that is worthy of use in commercial applications. Granted, most of the time, we'll only execute the "happy path", and there will be no problems with this lack of documentation. However, we shouldn't throw caution to the wind and assume everything will be OK.

    I can't help but think that this could have been avoided if QT would have embraced exceptions. Then, the API could avoid using C-like return codes and maintain its elegance but still report errors in a manner that is convenient for handling and documentation. QFileInfo::size() could be documented to throw QFileNotFoundException and QIOException, for example, making it easy for the user of the class to tell what happened. But they would have to rethink some of their code if they did this, because the naked-pointer-filled code that they have now would not be exception safe at all. I doubt that they will make the switch any time soon because everyone seems to be so happy with it the way it is today.
    1. Re:Design flaws in QT? by Jerry · · Score: 2, Insightful

      I've seen you post this question on QtCentre, too.

      Use QFileInfo::isFile to determine if the file exists, then QFileInfo::size returns the file size in bytes, or 0 or if the size is 0 or if the size cannot be fetched.

      What's so hard about that? You've never run into tri-states before?

      --

      Running with Linux for over 20 years!

    2. Re:Design flaws in QT? by AuMatar · · Score: 2, Insightful

      Returning a negative number for failure would have been better- you don't have to worry wether 0 means an empty file or an error, it would always mean an empty file, and < 0 would always mean an error. You could also then return different negative numbers for different error conditions. It may have a work around, but its a poor design.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    3. Re:Design flaws in QT? by bit01 · · Score: 2, Informative

      Use QFileInfo::isFile to determine if the file exists, then QFileInfo::size returns the file size in bytes, or 0 or if the size is 0 or if the size cannot be fetched.

      This is buggy. It is a race condition. If the underlying file is deleted or renamed or is replaced by a named pipe in between those two calls the return from both calls is inconsistent.

      This sort of error is unfortunately endemic in GUI code, not just qt, and is a large part of why GUI programs, are often flakey. GUI libraries usually have crappy kitchen sink API's that encourage bad programming practices; almost requiring numerous race conditions and potential security holes unless heroic programming efforts are made to avoid them. The kitchen sink API's are an attempt to improve productivity however a lot more care needs to go into their organisation to discourage bad programming practices, particularly race conditions. In this case they should've guaranteed the caching of all of QFileInfo so that all the information about the file is atomic, making race-free programming easier. Better, they should've had a handle to the file that guarantees that whatever operations are done on the file refer to the same file, including file operations outside of QFileInfo.

      ---

      Don't be a programmer-bureaucrat; someone who substitutes marketing buzzwords and software bloat for verifiable improvements.

  10. Re:Update on the link by rm999 · · Score: 2, Informative

    And your link doesn't have a referral tag (which I hate because I know those are the next popup windows of the internet).

    It's hard to write a bad review when you know you will make money if people buy it...

  11. Re:gui and native code - bad combination by Phisbut · · Score: 4, Informative
    I agree that if I want to put a label in a window, I dont want to have to handle its deallocation, i.e. I want a "fire-and-forget" feature. I accomplished this in my wrapper by letting the parent deal with its children.

    Well, that is exactly what Qt does. Every time you create a widget, you pass a pointer to its parent, and then you can forget about the widget. When the parent dies, it'll kill all of its children, and then they'll kill their children too in cascade. I do tons of Qt programming (that's what we use where I work), and memory management of Qt widgets is a breeze, every widget is hierarchically created, and I just need to kill the window when I don't need it anymore to have it kill all its widgets and sub-widgets. No need for a custom-made wrapper, it's all in there already.

    --
    After 3 days without programming, life becomes meaningless
    - The Tao of Programming
  12. Re:Qt in an Embedded (Non-Linux) Environment ? by Millenniumman · · Score: 2, Funny

    You'll have to enable the string parsing concatenation recompilation matrix kit, and possibly the array flattening engine libraries. If you want a GUI, you'll need to pass the build argument "QT_UNDECELERATE_FRAMEWORK". If your OS runs a non-57 bitrate clock register, you'll need to use type 874r function register matrix libraries. When you build you'll need to bypass kernel remapping protocol structures to endianize the unclock processor. Other than those steps, it shouldn't be too hard.

    --
    Stupidity is like nuclear power, it can be used for good or evil. And you don't want to get any on you.
  13. Re:Qt is very nice. by Almahtar · · Score: 2, Informative

    In my senior design class my last year of college, the project was to build a Windows app that did X, Y, and Z - any extra features and polish were left to the students' imaginations. The 3 students that used Qt did substantially better than the others, and their stuff ran on Windows, Mac, and Linux. None of them reported having to change a single line of source code porting from one platform to the next. The 6 Java people didn't do as well as the .net people overall, but their stuff ran on Mac most of the time. They reported spending some time and effort to get the Mac version working. The 8 .NET people by and large got better ratings than the Java people as far as features, usability, and speed, but their stuff only ran on Windows. So while the populations weren't large enough for anything vastly conclusive, it is a tribute to Qt that the 3 students using it did noticeably better than the 14 others just on windows, but also ran on Mac and Linux.

  14. Your learning experience will not be a killer app by dbIII · · Score: 2, Insightful
    Simple - you learn on the free version. If you are good enough you can then go commercial with a completely closed application and make money - but you have to feed the people who work at troll a bit too with some of this in the form of a licencing fee. If you are not sure it is good enough or you don't want to go through the hassle of convincing people to buy your stuff you release a completely open application. There is too much crap shareware in the world already - even if you write a gem how will people find it?

    However, there may be some cut price licences out there for shareware or you probably can turn your software written on the GPL Qt into the commercial version if you have never released the software and you get a commercial licence. Perhaps look at their website - I've only looked at their GPL stuff.

  15. Some Pointers by Uncle_Al · · Score: 2, Informative
    Almost every part of GTK+, from the colors to widget shapes, can be changed in user themes. Qt has no way to do either of these without linking in bloated external libraries.
    Well, I guess then the class QStyle is completely useless....and setting a "usertheme" with qt-config is something I must have dreamed then....*g*

    Until Qt 4, there was no way to load .ui files at run time.
    Ok...but what is the class QWidgetFactory used for then? :-)

    Qt still has no support for "recent documents", requiring the user to keep track of and build this list himself.
    Which is rather easy using QSettings...

    Have a nice day :-)

  16. QT licensing problems by pkphilip · · Score: 2, Interesting

    I have serious problems with the QT licensing model. I perfectly understand that they want to charge commercial developers for using their products. Heck, I won't even mind if they don't have a free version. But what I find absolutely intolerable are the terms of their commercial license.

    The commercial license is tied to a named developer. That is, if I have a developer Dave who needs a QT license, I must buy a named license for Dave. It does not matter if I have unused licenses of QT lying around (which other developers don't need and are not even installed), I must still buy a license for Dave.

    If Dave needs to go on a holiday or just dies and if I need Bill to complete the project using Dave's license, then the terms of the license prevents me from doing that. The license must be transferred over to Bill's name and this can be done only after 6 months! This is completely insane! Why would a company purchase a several-thousand-dollar license for a developer and face the prospect of having to purchase yet another license if the developer leaves the company / is unable to work on the project / is promoted to a non-coding role etc?

    QT's commercial license fees are very high, and separate licenses are needed for each platform - that is, I need to buy QT license separately for Linux, Windows etc. Now, I perfectly understand that Trolltech can charge what they want as it is their product, but I do feel that they have made the product as unattractive an option as possible and this has resulted in huge losses to them. But again, that is their problem not mine.

    I had the opportunity to review cross platform GUI toolkits for a huge project we were working on - the project was a very large public transportation project for Scandinavia and we needed a lot of licenses; I opted against QT (thereby denying them a huge order) because of these very unattractive terms in their licenses. I have had similar experiences with another project for a Finnish client as well. In both cases, I felt that QT was definitely the best framework for the job, but the licensing terms completely wiped out any of the technical advantages.

    The primary problem with the QT commercial license is the fact that it makes it very difficult to bring in developers on a contract into a project for a short assignment. It becomes very difficult to reuse this license with yet another developer once the first developer's contract ends or if the first developer chooses to go elsewhere.

    IMHO, Trolltech has an excellent product, but their legal and marketing departments needs to be overhauled.