Skip to content

Instantly share code, notes, and snippets.

@mitchcurtis
Created May 27, 2026 03:05
Show Gist options
  • Select an option

  • Save mitchcurtis/1c25f98ba8f3b35d5e931e1be1dedd81 to your computer and use it in GitHub Desktop.

Select an option

Save mitchcurtis/1c25f98ba8f3b35d5e931e1be1dedd81 to your computer and use it in GitHub Desktop.
Qt Quick auto test that shows the two potential points of failure when creating objects from QQmlComponent. Note that window.qml must go in a directory named "data".
cmake_minimum_required(VERSION 3.5)
project(tst_untitled LANGUAGES CXX)
enable_testing()
find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Gui Test Quick)
find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Gui Test Quick)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(tst_untitled tst_untitled.cpp)
add_test(NAME tst_untitled COMMAND tst_untitled)
target_link_libraries(tst_untitled
PRIVATE
Qt${QT_VERSION_MAJOR}::Gui
Qt${QT_VERSION_MAJOR}::Test
Qt${QT_VERSION_MAJOR}::Quick
)
#include <QtTest>
#include <QQmlEngine>
#include <QQmlComponent>
#include <QQuickWindow>
#include <memory>
class tst_untitled : public QObject
{
Q_OBJECT
private slots:
void testUniqueInstantiationError();
};
void tst_untitled::testUniqueInstantiationError()
{
QQmlEngine engine;
QQmlComponent component(&engine);
component.loadUrl(QUrl::fromLocalFile(QFINDTESTDATA("data/window.qml")));
QVERIFY2(component.isReady(), qPrintable(component.errorString()));
// Attempt creation with missing initial properties to force instantiation failure.
QVariantMap emptyProperties;
std::unique_ptr<QObject> rootObject(component.createWithInitialProperties(emptyProperties));
QVERIFY2(rootObject, qPrintable(component.errorString()));
}
QTEST_MAIN(tst_untitled)
#include "tst_untitled.moc"
import QtQuick
Window {
id: root
// This compiles successfully (loadUrl passes),
// but object instantiation will fail if this isn't supplied.
required property string mandatoryConfiguration
width: 640
height: 480
title: "Test Window"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment