qt | test qt application | Cell 3 | Search

The code initializes a Qt application by loading a QML string that describes a simple rectangle with a button, and then creates a QQuickWidget to host the QML content. The application is executed, and an alternative method is also demonstrated where the QML content is loaded from a data URL using the setSource function of the QQuickWidget.

Run example

npm run import -- "qt qml widget"

qt qml widget


#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QQmlEngine>
#include <QQmlComponent>
#include <QQuickWidget>
#include <QQuickItem>
#include <QQuickWindow>

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    // QML string defining a simple Rectangle
    QString qmlString =
        "import QtQuick 2.0\n"
        "import QtQuick.Controls 2.0\n"
        "Item {\n"
        "    width: 200\n"
        "    height: 100\n"
        "    Row {\n"
        "        anchors.centerIn: parent\n"
        "        Button {\n"
        "            text: \"Button 1\"\n"
        "            onClicked: { console.log(\"Button 1 clicked\") }\n"
        "        }\n"
        "    }\n"
        "}\n";

    // Create QML engine and component
    QQmlEngine engine;
    QQmlComponent component(&engine);
    component.setData(qmlString.toUtf8(), QUrl());

    // Check for errors
    if (component.isError()) {
        qDebug() << "Error loading QML:" << component.errorString();
        return 1;
    }

    // Create the QQuickItem
    QQuickItem *item = qobject_cast<QQuickItem*>(component.create());
    if (!item) {
        qDebug() << "Error creating QQuickItem";
        return 1;
    }

    // Create a QQuickWidget to host the QQuickItem
    QQuickWidget *quickWidget = new QQuickWidget;
    quickWidget->setResizeMode(QQuickWidget::SizeRootObjectToView);
    quickWidget->setSource(QUrl("data:text/plain," + qmlString)); //Alternative to using setData on component

    //Create main widget and layout
    QWidget *mainWindow = new QWidget;
    QVBoxLayout *layout = new QVBoxLayout(mainWindow);
    
    // Add the QQuickWidget to the layout
    layout->addWidget(quickWidget);
    mainWindow->setLayout(layout);
    mainWindow->show();

    return app.exec();
}

What the code could have been:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

class LlamaApp : public QApplication {
public:
    LlamaApp(int argc, char *argv[]) : QApplication(argc, argv) {}

    int run() {
        // Load QML string into QML engine and component
        QString qmlString =
            "import QtQuick 2.0\n"
            "import QtQuick.Controls 2.0\n"
            "Item {\n"
            "    width: 200\n"
            "    height: 100\n"
            "    Row {\n"
            "        anchors.centerIn: parent\n"
            "        Button {\n"
            "            text: \"Button 1\"\n"
            "            onClicked: { console.log(\"Button 1 clicked\") }\n"
            "        }\n"
            "    }\n"
            "}\n";

        QQmlEngine engine;
        QQmlComponent component(&engine);
        if (!component.setData(qmlString.toUtf8(), QUrl())) {
            QMessageBox::critical(nullptr, "Error", engine.toScriptString());
            return 1;
        }

        // Check for errors
        if (component.isError()) {
            QMessageBox::critical(nullptr, "Error", "Error loading QML: " + component.errorString());
            return 1;
        }

        // Create the QQuickItem
        QQuickItem *item = qobject_cast(component.create());
        if (!item) {
            QMessageBox::critical(nullptr, "Error", "Error creating QQuickItem");
            return 1;
        }

        // Create a QQuickWidget to host the QQuickItem
        QQuickWidget *quickWidget = new QQuickWidget;
        quickWidget->setResizeMode(QQuickWidget::SizeRootObjectToView);
        quickWidget->setSource(QUrl("data:text/plain," + qmlString));

        // Create main widget and layout
        QWidget *mainWindow = new QWidget;
        QVBoxLayout *layout = new QVBoxLayout(mainWindow);

        // Set up the QQuickWidget to be automatically resized
        layout->setContentsMargins(0, 0, 0, 0); // Remove padding to ensure proper resize
        quickWidget->setMinimumSize(200, 100); // Minimum size for the widget
        quickWidget->show();

        // Add the QQuickWidget to the layout
        layout->addWidget(quickWidget);
        mainWindow->setLayout(layout);
        mainWindow->show();

        // Initialize QTimer to periodically check for errors
        QTimer timer;
        QObject::connect(&timer, &QTimer::timeout, [engine] {
            if (engine.toScriptString().isEmpty() || engine.hasError()) {
                qDebug() << "QML engine is not responding";
            }
        });

        return exec();
    }
};

int main(int argc, char *argv[]) {
    LlamaApp app(argc, argv);
    return app.run();
}

Code Breakdown

Includes

The code includes the following Qt libraries:

Main Function

The main function is the entry point of the application.

  1. Application Initialization: The QApplication object is created with the command line arguments.
  2. QML String: A QML string is defined, which describes a simple rectangle with a button.
  3. QML Engine and Component: A QQmlEngine object is created, and a QQmlComponent object is created with the QML engine.
  4. QML Component Loading: The QML string is loaded into the component using the setData function.
  5. Error Checking: The component is checked for errors, and if there are any, the error message is printed to the console and the application exits.
  6. QQuickItem Creation: The QML component is created as a QQuickItem object.
  7. QQuickWidget Creation: A QQuickWidget object is created to host the QML content.
  8. Main Window Creation: A QWidget object is created as the main window, and a QVBoxLayout object is created to manage the layout.
  9. QQuickWidget Addition: The QQuickWidget is added to the layout, and the layout is set as the main window's layout.
  10. Application Execution: The application is executed with the exec function.

Alternative QML Loading

The code also demonstrates an alternative way to load the QML content using the setSource function of the QQuickWidget, which sets the QML source to a URL. In this case, the QML content is set as a data URL with the data:text/plain scheme.