Reader small image

You're reading from  Mastering Qt 5 - Second Edition

Product typeBook
Published inAug 2018
Reading LevelIntermediate
PublisherPackt
ISBN-139781788995399
Edition2nd Edition
Languages
Tools
Right arrow
Authors (2):
Guillaume Lazar
Guillaume Lazar
author image
Guillaume Lazar

Guillaume Lazar is a software engineer living in France, near Paris. He has worked in different companies, from start-ups to multinationals, for the last 10 years. He took the opportunity to observe and learn many team organizations and technologies. In 2014, he founded his own software development company at the age of 27. The current hierarchical organization that applies to most companies seems obsolete to him. With his own company, he wants to try a different approach. Although he defines himself as a Qt framework lover, he likes to mix different technologies and platforms. He also spends time on game development, machine learning, and electronics, because "things" become "alive".
Read more about Guillaume Lazar

Robin Penea
Robin Penea
author image
Robin Penea

Robin Penea has been working in the software industry for a more than a decade. He worked in start-ups and large companies with many technologies that ranged from embedded software to web development. Armed with this experience, he wrote the Mastering Qt 5 book to spread what he loves the most about the programming craft: proper design and quality code. The teaching bug has bitten him, and he continues to share what he learned online using videos. When he is not tinkering with some new technology, he is either on a wall, rock-climbing, or playing music on his piano. You can reach him via Twitter @synapticrob.
Read more about Robin Penea

View More author details
Right arrow

Third-Party Libraries without a Headache

In previous chapters, we used our own libraries or the ones provided by Qt. In this chapter, we will learn how to integrate the third-party library OpenCV with a Qt project. This library will give you an impressive image processing toolbox. For each platform, you will learn to use a specific compiler link configuration.

Qt Designer is a powerful WYSIWYG editor. This is why this chapter will also teach you to build a Qt Designer plugin that can be dragged and dropped from the Widget Box to the Form Editor, and then configured directly from Qt Creator.

In the example project, the user can load a picture, select a filter from thumbnail previews, and save the result. This application will rely on OpenCV's functions for image processing.

This chapter will cover the following topics:

  • Creating your Qt Designer plugin
  • Implementing your OpenCV...

Creating your Qt Designer plugin

In Chapter 4, Conquering the Desktop UI, we created a custom Qt widget in Qt Designer using the promoting technique. It is now time to learn how to create a custom Qt widget by building a plugin for Qt Designer. Your widget will be available from the Design mode in the Widget Box, alongside other regular Qt widgets. For this project example, we will create a FilterWidget class that processes an input image to apply a filter. The widget will also display the filter name and a dynamic thumbnail of the filtered picture.

This project is composed of two subprojects:

  • filter-plugin-designer: This is a Qt Designer plugin containing the FilterWidget class and the image-processing code. This plugin is a dynamic library that will be used by the Qt Creator to offer our new FilterWidget in the Form Editor.
  • image-filter: This is a Qt widget application using...

Configuring the project for Windows

Before preparing this project on Windows, let's talk about the available choices when you develop a Qt application on a Windows host. The official Qt website provides multiple binary packages. We are mainly interested in the following:

  • Qt for Windows 32-bit (MinGW)
  • Qt for Windows 32-bit (VS 2013)

You may already be using one of these versions. The first one comes with a MinGW GCC compiler and the Qt framework. The second only provides the Qt framework and relies on the Microsoft Visual C++ compiler that will be installed with Visual Studio.

Both versions are fine when you want to create a common Qt application for Windows. However, for this chapter, we want to link our filter-plugin-designer project with OpenCV libraries. Qt Designer must also be able to dynamically load filter-plugin-designer, so we must use a consistent compiler version...

Configuring the project for Linux

OpenCV binaries are certainly available in official software repositories. Depending on your distribution and your package manager, you can install it with commands such as the following:

# On Debian system    
apt-get install libopencv-dev

# On Red Hat system yum install opencv

When OpenCV is installed on your Linux, you can add this snippet to the filter-plugin-designer.pro file:

linux { 
    target.path = $$(QTDIR)/../../Tools/QtCreator/lib/Qt/plugins/designer/ 
     CONFIG += link_pkgconfig 
    PKGCONFIG += opencv 
} 

This time, we do not use the LIBS variable but PKGCONFIG, which relies on pkg-config.

It is a helper tool that will insert the correct options into the compile command line. In our case, we will request pkg-config to link our project with OpenCV.


You can list all the libs managed by pkg-config with the pkg-config --list-all...

Configuring the project for Mac

The first step in making the project work on Mac OS is to install OpenCV. Fortunately, this is very easy using the brew command. If you develop on Mac OS and do not use it already, you should download it right now. In a nutshell, brew is an alternative package manager that gives you access to many packages (for developers and non-developers) that are not available in the Mac App Store.


You can download and install brew from http://brew.sh/.

In a Terminal, simply type the following command:

 brew install opencv

This will download, compile, and install OpenCV on your machine. At the time of writing, the latest OpenCV version available on brew was version 3.2. Once this is done, open filter-plugin-designer.pro and add the following block:

macx { 
    target.path = "$$(QTDIR)/../../QtCreator.app/Contents/PlugIns/designer/" 
    target_lib...

Implementing your OpenCV filters

Now that your development environment is ready, we can begin the fun part! We will implement three filters using OpenCV:

  • FilterOriginal: Does nothing and returns the same picture (lazy!)
  • FilterGrayscale: Converts a picture from color to grayscale
  • FilterBlur: Smooths the picture

The parent class of all these filters is Filter. Here is the abstract class:

//Filter.h
class Filter
{
public:
    Filter();
    virtual ~Filter();

    virtual QImage process(const QImage& image) = 0;
};

//Filter.cpp
Filter::Filter() {}
Filter::~Filter() {} 

As you can see, process() is a pure abstract method. All filters will implement a specific behavior with this function. Let's begin with the simple FilterOriginal class. Here is FilterOriginal.h:

class FilterOriginal : public Filter
{
public:
 FilterOriginal();
 ~FilterOriginal();

QImage process(const QImage...

Designing the UI with FilterWidget

Fine. Our filter classes are implemented, and we can now create our custom widget. This widget will take as inputs: a source picture and a thumbnail picture. Then the thumbnail will be immediately processed to display a preview of the filter. If the user clicks on the widget, it will process the source picture and trigger a signal with the filtered picture. Keep in mind that this widget will later be dragged and dropped in the Form Editor of Qt Creator. That's why we will provide properties with getters and setters to select a filter from Qt Creator. Let's create a new widget called FilterWidget using the Qt Designer Form Class template. The FilterWidget.ui is really simple, as you can see in the following screenshot:

The titleLabel is a QLabel on top of the QWidget. In the following code, thumbnailLabel will display the filtered...

Exposing your plugin to Qt Designer

The FilterWidget class is completed and ready to be used. We now have to register the FilterWidget class with the Qt Designer plugin system. This glue code is made using a child class of QDesignerCustomWidgetInterface.

Create a new C++ class named FilterPluginDesigner and update FilterPluginDesigner.h as shown in the following code:

#include <QDesignerCustomWidgetInterface> 
 
class  FilterPluginDesigner : public QObject, public QDesignerCustomWidgetInterface 
{ 
    Q_OBJECT 
    Q_PLUGIN_METADATA(IID 
        "org.masteringqt.imagefilter.FilterWidgetPluginInterface") 
    Q_INTERFACES(QDesignerCustomWidgetInterface) 
public: 
    FilterPluginDesigner(QObject* parent = 0); 
}; 

The FilterPlugin class inherits from two classes:

  • The QObject class, to rely on the Qt parenting system
  • The QDesignerCustomWidgetInterface class, to...

Using your Qt Designer plugin

Our custom plugin is now finished. Because we added a custom Build command to automatically deploy the filter-widget library, it should be visible in Qt Designer. The deploy path we specified is inside the Qt Creator directory. Qt Creator integrates Qt Designer via a plugin that displays the UI inside Qt Creator.

When Qt Creator starts, it will try to load every library available in its specific paths. This means that you have to restart Qt Creator each time you modify the plugin (if you want to see the result of your modifications in the designer).

To see the plugin in action, we now have to create the application project of the chapter. Create a Qt Widgets Application subproject in the ch07-image-filter project named image-filter. In the wizard, let it generate the form, called MainWindow.ui.

To properly use the plugin, just link the filter-plugin...

Building the image-filter application

We can proceed to build the UI of the application. The idea is to open a picture from the filesystem and apply to it the various filters we developed in the filter-designer-plugin project. If you want to keep the result, you can save the resulting image.

We will start by designing the UI. Modify MainWindow.ui to look like the following:

Here is the Object Inspector content to help you build this layout:

There are three elements of this UI:

  • The menuFile element, which contains three possible actions: actionOpenPicture, actionExit, and actionSaveAs. You can see the details of these actions in the Action Editor window.
  • The pictureLabel element, which will display the loaded picture in the empty top section.
  • The filtersLayout element, which contains the three instances of our FilterWidget class in the bottom section.

As you add a FilterWidget...

Summary

In this chapter, you learned how to integrate a third-party library with each desktop OS (Windows, Linux, and Mac OS). We chose the OpenCV library, which has been included in a custom Qt Designer plugin and which can display a live preview of your image processing result in Qt Designer. We created an image-filtering application that can open pictures, apply filters to them, and save the result on your machine.

We had a good look at how you can integrate third-party libraries and how you can make a Qt Designer plugin. In the next chapter, we will push things forward by making the image-filter application ready to load filter plugins that could be implemented by third-party developers. To make things even cooler, we will cover the Qt animation framework to make the image-filter more spectacular.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering Qt 5 - Second Edition
Published in: Aug 2018Publisher: PacktISBN-13: 9781788995399
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
Guillaume Lazar

Guillaume Lazar is a software engineer living in France, near Paris. He has worked in different companies, from start-ups to multinationals, for the last 10 years. He took the opportunity to observe and learn many team organizations and technologies. In 2014, he founded his own software development company at the age of 27. The current hierarchical organization that applies to most companies seems obsolete to him. With his own company, he wants to try a different approach. Although he defines himself as a Qt framework lover, he likes to mix different technologies and platforms. He also spends time on game development, machine learning, and electronics, because "things" become "alive".
Read more about Guillaume Lazar

author image
Robin Penea

Robin Penea has been working in the software industry for a more than a decade. He worked in start-ups and large companies with many technologies that ranged from embedded software to web development. Armed with this experience, he wrote the Mastering Qt 5 book to spread what he loves the most about the programming craft: proper design and quality code. The teaching bug has bitten him, and he continues to share what he learned online using videos. When he is not tinkering with some new technology, he is either on a wall, rock-climbing, or playing music on his piano. You can reach him via Twitter @synapticrob.
Read more about Robin Penea