Replacing QNetworkAccessManager for the great good

Everybody using Qt for networking for small tasks will sometimes face oddities of QNetworkAccessManager. This class aims to be useful and convenient while having few quite sensible drawbacks. First one of couse is inability to use it in blocking way. What you should do instead is to create instance of QEventLoop and connect it’s quit() signal with network manager.

QNetworkAccessManager networkManager;
QEventLoop loop;
QNetworkReply *netReply = networkManager.get(resource);
connect(netReply, SIGNAL(finished()), &loop, SLOT(quit()));

This is overkill and overengineering of course. This inconveniency strikes also when you try to use it from background thread for downloading something – QNetworkAccessManager needs an event loop and it will launch one more thread – it’s own to do all the operations required.

Also it has a lot of data, methods and abilities not needed for “everyday simple network operations” like querying some API or downloading files. I don’t know anybody who wasn’t looking for a substitude for it at least once. But fortunately the solution exists.


Implementing spellchecking in desktop application in C++

When user is supposed to enter significant amount of text in your application, it’s better to help him/her to control it with checking spelling. Basically, to check spelling you need a dictionary with words and algorithm to order these words. Also it might be useful to provide user with possible corrections for any spelling error. Here where Hunspell comes handy. It’s an open source library built on top of MySpell library and used in a significant number of projects varying from open source projects like Firefox to proprietary like OS X. It contains bindings to a number of platforms (.NET, Ruby etc.) and should be fairly easy to integrate to your project. In this post I’ll discuss how to integrate it to C++/Qt project.


Classic Producer-Consumer in Qt/C++

Producer-Consumer is a classic pattern of interaction between two or more threads which share common tasks queue and workers who process that queue. When I came to similar task first I googled for standard approaches in Qt to solve this problem, but they were based on signals/slots plus synchronization primitives while I wanted simple and clear solution. Of course, in the end I’ve invented my own wheel and I invite you to take a look at it.

For the synchronization in Producer-Consumer it’s useful to use Mutex and some kind of WaitingEvent for synchronous waiting until mutex is acquired. In Qt you have QMutex and QWaitCondition which are all that we need.

Let’s suppose we have following data structures:

        QWaitCondition m_WaitAnyItem;
        QMutex m_QueueMutex;
        QVector<T*> m_Queue;

where T is type of messages we’re producing/consuming. So we have queue of elements being processed, mutex to secure access to the queue and wait condition to wait if the queue is empty.

For Producer-Consumer usually we need methods produce() and consume(). Let’s see how we can implement them.


Handling drag’n’drop of files in Qt under OS X

If you ever tried to handle drag’n’drop files in your Qt application, you would usually come up with the code like the following.
First of all you will need a Drop Area somewhere in your application, which will handle drops

DropArea {
  anchors.fill: parent
  onDropped: {
    if (drop.hasUrls) {
      var filesCount = yourCppModel.dropFiles(drop.urls)
      console.log(filesCount + ' files added via drag&drop')

Where yourCppModel is a model exposed to Qml in main.cpp or wherever like this:

QQmlContext *rootContext = engine.rootContext();
rootContext->setContextProperty("yourCppModel", &myCppModel);

and int dropFiles(const QList<QUrl> &urls) is just an ordinary method exposed to QML via Q_INVOKABLE attribute.

You will sure notice everything works fine unless you’re working under OS X. In OS X instead of QUrls to local files you will get something like this: file:///.file/id=6571367.2773272/. There’s a bug in Qt for that and it even looks closed, but it still doesn’t work for me that’s why I’ve implemented my own helper using mixing of Objective-C and Qt-C++ code.


Interesting issues and features of Qt programming

In this post I enlist all interesting facts and issues I’ve experienced while developing my first project in Qt (from 5.3 to 5.4 5.6)

18.02 – QSettings interface in Qml transformed bool to string and was always true on deserialization

18.02 – QByteArray returned from local scope crashed with heap corruption on return of function (destructor of QByteArray)

Qt can delete your object in it’s gui loop. QObject should have CppManaged attribute and it should be set before returning object to UI code.

26.02 QTimer can be only started when EventLoop is already running (e.g. with app.exec()) otherwise you get an error “QTimer can be started in QThread”

Drag and Drop files in OS X inserts NSUrl instead of QUrl and you have to convert it using Objective C to real filepath. You can add .m file to Qt project and write C++/Objective-C code.

23.03 QtConcurrent::mapped can accept a struct with operator() but only with inner typedef T return_type; where T is mapped type for correct QFuture<T> conversion. Also, QtConcurrent::mapped cannot be cancelled.

30.05 Qt Column allows to do animations, but has issues with stretching and ColumnLayout has no issues with stretching, but doesn’t allow you to do animations. I had to use simple anchors layout and States with Transitions to animate properties I wanted

1.06 Qt ListView has Transitions add/remove/removeDisplaced/displaced/etc, which allow to create nice animations for adding/deleting items from listview and to make UI really nice

6.06 Qt lacks standard Zip/Unzip functionality. QuaZip makes life easier, but has minor issues with compilation (linking etc).

22.07 TextInput’s EditingFinished signal fires twice in OS X

6.09 Windeployqt does not pack qml dlls into the bundle, you have to do it manually from your <Qt-bin-dir>/qml. You need to copy QtQuick and QtQuick2 directories and others which you use

19.09 Tab control is a loader and you can’t access it’s child object by Id. You have to create a property of Tab and do double binding inside and outside Tab to that property.

25.10 Repeater in GridLayout does not respect QAbstractItemModel changes, but does respect once put into Flow

23.11 Always initialize boolean fields, volatile or not. Always do that because in other case you will get tons of unpredictable behavior.

28.11 Use QVector instead of QList for most types. If you have released public version with wrong type and users depend on it, you’re screwed

12.12 QML ListView fails to update itself after sophisticated filter/remove operations. You have to manually positionViewAtBeginning() stuff

20.03 QFile in Windows does not respect flag QIODevice::Unbuffered because of “lack of native support in Windows” (bullshit) as of Qt 5.6

21.03 QProcess has super strange problems. Exiftool does not work with unicode from QProcess but works when launched via cmd.exe

2.05 QWaitCondition destructor produced a warning that it’s destroyed while inner Mutex is still locked. Was able to debug that using export QT_FATAL_WARNINGS=true in the running environment

20.07 QString::fromLatin1() truncated buffer of QByteArray parameter if the latter contained some eol/nl characters

16.12 virtual inheritance from the QObject is not supported.. Need to have stubs for calling signals

17.03 Timer in QML can have very high CPU utilization. Need to use with care

Text encryption in Qt/C++ with tiny AES 128bit

Have you ever needed a small, really small encryption in your C++ project for some piece of text? Say, credentials, login details or any other sensitive data? Of course, the best way is to keep just hash of salted password, but… What if you just need to do it and the size is so much critical for you?

There’re openSSL library and Crypto++ library which are monsters with tons of encryption algorithms, used in a number of solid projects etc. But.. they are big! I don’t want 30Mb library in my tiny project, which weights 10 Mb with high-resolution icons for OS X which weight by itself 5Mb. So I don’t want to sacrifice the size but still need encryption. Meet tiny-AES. It’s really small AES 128-bit library which does encryption in CBC and ECB modes. It really contains everything you needed just to encrypt and decrypt your sensitive data and forget about it.

You can find example under the hood.