Qt 5: how to make a "pure c++" client socket?

917 views Asked by At

I am building a QtQuick app, and i need a TCPSocket that polls a device and fills the data structures I want to show. I've found a lot of samples about sockets and Qt 5 widgets, but i'm not able to create the socket as a C++ class that's not derived from QObject.

My understanding is that I only need to derive from QObject if I want to exchange data with my QML view. I wrote an additional class that does that, so my socket class doesn't have a need to pass any data to my QML code.

1

There are 1 answers

0
Kuba hasn't forgotten Monica On

The question almost doesn't seem to be a Qt question, but a C++ network programming question. I gather that you basically dislike explicitly using custom QObject-derived classes since you don't want to run moc as a part of your build process. While one might argue what's so bad about it, since moc is run a whole lot during the building of Qt proper, let's go with what's asked for the moment.

If you're looking for non-Qt-based pure-C++ networking, then Boost ASIO is a very solid solution.

If you wish to use Qt networking without a custom QObject-derived class, then you can run the code in a separate thread and only use blocking QTCPSocket calls. After all, it's a QIODevice and offers blocking interface.

Eventually, you end up with some data structure that's filled and should be passed on to QML.

Logically your data is a data model, and the view is in the QML code. You can use QStandardItemModel for that - that is, if you are writing true model-view code, like you would if the data will change over time. Again, you're re-using an existing QObject-derived class, without deriving your own, without writing any custom signals nor slots.

A really poor-man's workaround is to take a naked QObject and put data in it using the dynamic property system via QObject::setProperty. I don't recall offhand if dynamic property changes are seen via the QML engine, you'd need to verify that or simply treat such objects as constants.

All of this seems to be a lot of workarounds for a rather silly reservation. Code generators are good, they save time. The build process of a complex C++-based product may use several different code generators, such as lexer/parser generators, state machine generators, remote procedure call generators, table generators, test case generators, etc. As C++ matures, ways are found to coax the compiler to replace some of those generators, but that's merely pushing the problem to a different executable, and sometimes pushing it through a very small needle hole as well.