Question

I have a C++ application already coded and its interface has been made with wxWidgets library. I would like to create a new interface with Qt creator.

My question is: how can I bind the C++ code with the new Qt interface?

Was it helpful?

Solution

Since you already have working logic, I suggest using QtQuick which is based on data binding. Although there's another technology named QtWidgets which is more classic, separation of logic/view is a bit weaker compared to QtQuick.

3 key concepts to get started with QtQuick with C++ binding are Q_PROPERTY / Q_INVOKABLE macros and qmlRegisterTypes method.

  • apply Q_PROPERTY to your getter / setter which shoud interact with GUI
  • apply Q_INVOKABLE to your method which should be called from GUI
  • qmlRegisterTypes enables you to use your C++ type inside GUI markup files (.qml files)

It looks like below:

public class YourLogicClassWrapper : public QObject {
 Q_OBJECT
 Q_PROPERTY(int yourData READ yourData WRITE setYourData NOTIFY yourDataChanged)
  signals:
   yourDataChanged();
  public:
   Q_INVOKABLE void yourMethodInvokedFromGUI(int) { /* ... */ }
   // ... you need to write getter "yourData()" and setter "setYourData(int)"
};

int main(int argc, char** argv) {
{
  qmlRegisterTypes<YourLogicClassWrapper>("YourModule", 1, 0, "YourQmlElem");
  // ... read qml file and display window etc. all generated by QtCreator

Once above are done, in .qml files, your field is visible and assignable, and your method callable.

Import QtQuick 2.2
Import YourModule 1.0
Item {
  YourQmlElem {
    id: y
    yourData: 42
  }
  Button {
    onClicked: y.yourMethodInvokedFromGUI(1)
  }
  // ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top