Qt4 Designer and Eclipse

PJ Radcliffe

Issue #209, September 2011

You don't have to be a code guru to develop GUIs.

Qt4 Designer is one of the most powerful GUI builders on the market. If you look at the many Qt4 Designer tutorials, they are all very code-heavy, which really puts off new programmers. After some searching, I put together a few simple methods that make GUI development easy, even for novice C++ programmers, and for experts, it will speed up development.

This article shows how to use a GUI builder based on Qt4 Designer and Eclipse. Unlike other tutorials, this one is not code-heavy; instead, it describes several simple methods that will enable you to develop a GUI in a visual manner with a minimum of C++ code. If you are new to C++ and GUI building, this tutorial will make it possible for you to build a GUI. If you are an expert, these methods at least will help speed your development. The development tools must run under the KDE desktop, although the final program can be run on a GNOME desktop as well.

GUI interfaces are a key part of most operating systems, and with Linux, we are spoiled for choice. So many good tools are available; see the Wikipedia IDE comparison in the Resources section of this article for an excellent summary. I teach some 300 first- and second-year engineers about Linux programming including GUI programming. They need to use C++, and the options tend to be narrow. The two IDEs that look most applicable are Code Blocks and the combination of Eclipse CDT and Qt4 Designer. Qt4 Designer clearly is the most powerful GUI builder with the best documentation, and it's free if you are creating GPL or LGPL code.

Installing the Software

The simplest option is to obtain a live DVD with all the necessary tools installed. See interestingbytes.wordpress.com for a Mint-based live DVD with these tools plus many other development tools.

To install the software yourself, work through the following steps:

First, ensure you have the gcc compiler toolchain installed. From a command line, type g++ --version. If this fails, use your package manager to install gcc, g++ and libstdc.

Next, you need the GUI builder Qt4 Designer and the documentation system Qt4 Assistant. You can find them in your Linux repository and install them with your package manager. In the unlikely event that Qt4 is not available, try the Nokia Qt download site (see Resources).

You also need Eclipse with CDT (C/C++ Development Tools) installed. There are several options here:

  • Install Eclipse CDT from your package manager (easiest option).

  • If you already have Eclipse installed but not the C/C++ development tools, start Eclipse and select the menu option Help→Install New software. Select your main repository site and filter on “CDT”. Select the CDT package and install.

  • The latest version of Eclipse at the time of this writing is Helios, which may not be in your distribution's repository. It has a nice all-in-one package of Linux Tools that includes code coverage and profiling. The Eclipse Helios site has a download and installation instructions (see Resources). Note the wiki link from that page, which has some very useful tutorials.

Finally, you need the Qt4 integration plugins for Eclipse. The Nokia Web site has instructions and the download (see Resources).

Creating a GUI Project

Most Qt4 tutorials show how to write code to build a form. The combination of Qt4 Designer and Eclipse means you can do this in a purely visual manner, which is faster and easier. To build your own GUI, work through the following steps:

  • Start Eclipse using the Linux Menu option Development→Eclipse. If any projects are open, select the Project Explorer in the left-hand panel, right-click on the project folder, then select Close Project.

  • From the Eclipse menu, select File→New→Project.

  • Find the Qt option, select the sub-option Qt GUI project, and then click Next.

  • On the next panel, provide a project name (let's use demo_1 for this example), and click Next (not Finish).

  • The next panel will set up the class and filenames. You can change the name of the class where you place your code. The bottom list box labeled UI Type is the most important field. It determines the type of GUI you will create. A Widget is a basic panel with no special functions; a Qdialog provides simple interaction with a user, and a QmainWindow is a panel with menus and other features. For this example, select QmainWindow, then click Next.

  • This panel allows you to include extra Qt modules—for example, a network interface or SQL interface. For this example, the extra modules aren't needed, so just click Finish.

  • You will be asked to accept Qt perspectives; click yes.

You now should have a GUI project ready to add visual components. To see the appropriate files, as shown in Figure 1, expand the project in the Project Explorer panel to the left and double-click on demo_1.ui.

Figure 1. Empty Main Page

The compile and execution of the GUI you have just created may have a hiccup, especially the first time you run it. You should be able to select from the Eclipse menu File→Save All, Project→Build All, and then Run→Run. If Run→Run is grayed-out, try the following:

  • If demo_1.cpp is not already in the editor window, then in the Project Explorer panel on the left, double-click demo_1.cpp to get the code in the editor window.

  • Add a space anywhere, and then from the Eclipse menu, select File→Save All.

  • Select Project→Build All, then Run→Run. If you are asked for a debugger configuration, choose gdb/mi.

  • Your GUI now should appear. Close it by clicking the close icon on the top right.

Now, it's time to add visual components to your bare form. On the left-hand panel, select the Qt tab to see the visual components. Click and drag across two Push Buttons, an LCD Number, a Text Edit box, a Horizontal Slider and a Progress Bar to get a form similar to Figure 2.

Figure 2. Visual Components

You can see the properties of any visual component by clicking on a component and then examining the property editor in the right-hand panel. The properties are shown as a hierarchy with the parent class first and then the child classes. You may need to scroll down to find the property you want to change. In Figure 2, a button has been selected and the property editor shows its properties. The property called “text” has been changed to MyButton, which is not the name of the button, just the message displayed. It's worth spending some time looking at all the properties you can alter. Try also right-clicking on visual components to see what you can change. For example, right-click on the text edit box and select Change HTML. Type in some text, click OK, and that text is now displayed in the text edit box.

To create a menu for your form, click at the top left where it says “Type Here”, and type “File”. Your form now has a menu option “File”.

Click on this again, and add a sub-option “Save”. After finishing this tutorial, it's worth starting a new project and playing with a range of visual components, right-clicking on each and changing the properties.

Qt Designer has the concept of signals and slots. A class can emit a signal when it has done something—for example, when a button is clicked. A class can accept a signal in a slot—for example, the LCD display has a slot to accept a new value. You can connect visual components directly together using signals. From the Eclipse menu, select Qt Designer→Editor Mode→Signals and Slots. Click on the slider, drag the resulting red line to the progress bar, and release the mouse. In the panel that pops up, select sliderMoved in the left box and setValue in the right box, then click OK. It's important to know this edit mode, because it's a quick way to discover all the signals and slots a visual component can support. To see what signals a button can generate, drag the mouse from the button to the form and release the mouse. A window now pops up that names all the signals a push button can emit. Close this window by pressing cancel to delete the link. Now, try dragging from the form to the button to see all the slots the button can support. Try doing the same to the LCD display (see Resources for more details on slots and signals).

Figure 3. Wired Signal

To run your GUI, first change the editor mode back to the normal widget view with Qt Designer→Editor Mode→Widgets. Then, compile and run using the Eclipse menu options File→Save All, Project→Build Project and Run→Run. If all goes well, you should get a result like what's shown in Figure 4. Try moving the slider, clicking on the buttons (which do nothing), and then close the window.

Figure 4. First Run

I don't have space to cover layout tools and spacers, which ensure that your layout expands and contracts as a user resizes the GUI window. See the large e-book from Blanchette and Summerfield, the short Layout Tutorial and the Qt Overview listed in the Resources section for more information. Qt Assistant, discussed later in this article, also has an excellent tutorial.

Adding Your Own Code

Other Qt4 tutorials become code-heavy at this point and lose people who are not experienced C++ programmers. Here, I explain how to link your code to the GUI interface in a simple and pain-free manner with minimal C++.

Adding code to a GUI project is not like writing code for a command-line program. Your code must be placed in the class created for you, in the example demo_1.cpp, not a main() routine. You should alter only demo_1.cpp, demo_1.h or demo_1.ui. The other files are generated automatically and will be overwritten on the next build.

Your code can be started only when a GUI event happens and it is linked to your code, or when a timer you have created times out. Furthermore, your code must do its job quickly and return. If your code delays, the entire application freezes and stops responding to user stimuli. These factors require you to design your code differently from how you would design a command-line program. When you write a GUI program, plan for all of your code to respond to GUI events and timers. The GUI package handles the rest for you.

Most GUI systems have a library of useful classes, and it's very much worth learning how to use those classes, as they can save you a lot of time and provide features you could not implement otherwise. The library with Qt Designer is particularly powerful and worth mastering (more on that later).

Now, let's add the links between your own code and the visual components. Click the demo_1.h tab, and add the single #include line at the top of Listing 1. Next, add the declaration for timer, the public slots section and functions that are called when signals are generated. These slots are all of the form on_objectName_action(). The available “action” can be discovered from what you did to create Figure 3. The first two slots are called when the buttons are clicked, the next when the form's menu item Save is selected, and the final one when your own timer based on Qtimer ticks. In total, you must add seven lines of code to the existing file.

Now, you can link the timer to the LCD display. In the demo_1.cpp file, modify the constructor to add the three lines of timer setup, as shown in Listing 2. First, the timer is created, and then the timer tick signal is connected to your own routine timer_tick(). Finally, the timer is set up to tick at 1,000 milliseconds (one second).

Listing 3 shows the code to react to the first push button. You need to add all the lines, as this member function is new. The first two lines of code change the text in the button and the font type. The next few lines change the color. This is well beyond what a simple application will need to do, but it shows a little more of what is possible.

Note that the properties of any visual component can be changed using the format ui.ComponentName->member_function(). As you begin to write more complex applications, you will need to find these member functions. The simplest way is to start a separate application called Qt Assistant, by going to Development→Qt4 Assistant from the Linux menu. As shown in Figure 5, click the Index tab and enter the name of the visual element. A detailed description of the element will be displayed, including all useful member functions. If you are serious about mastering Qt Designer, it's worth spending some time working through the Qt Assistant documents. In particular, click the Contents tab, and open the Qt Designer Manual, which includes a wealth of useful tutorials and examples.

Figure 5. Qt Assistant

The second push button also must have its member function created (Listing 4). Again, the code shown here is more complex than a simple application needs to be, but it shows a very useful feature: calling a command-line program.

Let's work through the code. Note how the text box on-screen is cleared. The ui.textEdit gives you access to the visual component, and the member function clear() is called. QbyteArray is an advanced C++ string type object. The QProcess object enables you to run a command-line program. First, the working directory is set, and then the command started. If it returns within 300 milliseconds, the result is written into the textEdit box; otherwise, the command is terminated, and the default error message is printed. Note that the returned text from the command line may have nonprinting characters, such as line feeds. To solve this problem, look up the QbyteArray member function simplified() in Qt Assistant.

To respond to the menu on the window, add:

void demo_1::on_actionSave_triggered()
{ ui.textEdit->clear() ;
  ui.textEdit->append("Menu item Save just triggered.") ;
}

To increment the LCD display every second, add:

void demo_1::timer_tick()
{ ui.lcdNumber->display( ui.lcdNumber->intValue() + 1) ;
}

Now, let's run your program. From the Eclipse menu, go to File→Save All, Project→Build Project and, finally, Run→Run. The LCD timer should be incrementing every second. Try clicking on the buttons and the form menu to make sure they perform as expected.

What Next?

What happens next is up to you. If you have trouble creating the example described here, you can download all of it from www.pjradcliffe.wordpress.com, then click on the “Other Useful Resources” page. Place the new directory inside the workspace directory (/home/user/workspace), then start Eclipse.

Browsing through Qt Assistant is a good way to discover the useful member functions of visual components and the other powerful classes, such as QbyteArray. Qt Assistant has many tutorials and examples, and the Web is a great source of information, as Qt has a vibrant user community. It won't take you long to make those visual components perform just as you wish.

Conclusion

After reading this article, you should be able to create a GUI using Eclipse and Qt4 Designer, mostly by visual manipulation of visual components plus a little C++ code. The example given here shows how to call your own code when visual components are activated (as with a button click), how to start your own code with a timer tick, and how to call command-line programs and read back their responses. You can do a lot with just those functions.

Dr PJ Radcliffe is a senior lecturer at RMIT University in Australia. He once was an ardent Windows programmer, but then he discovered Linux, which he now teaches along with the control of hardware using Linux. If you are interested in these topics, see www.pjradcliffe.wordpress.com.