C-RUN Runtime Analysis in Stand-Alone Mode

C-RUN is a runtime analysis tool which works as an add-on to IAR Embedded Workbench for ARM. C-RUN can detect possible errors such as overflow, boundary errors and memory usage errors.

The error messages are displayed in the debug window. However, C-RUN messages can be redirected to any communication channel, and messages can be captured in the field test and checked after the test.

How to Validate a Build Toolchain According to IEC 61508, ISO 26262, EN 50716 and IEC 62304

We offer certified versions of the build chain in IAR Embedded Workbench for Arm, RISC-V, STM8, Renesas RX, RL78 and RH850 for use in safety-critical applications according to IEC 61508, ISO 26262, EN 50716 and IEC 62304. In this article, we will take a look at what the certification means and how you can take advantage of the certification in your own projects. The included functional safety services can actually be valuable whether you are formally certifying your application or not.

Embedded standards

Formal standards for safety certification have been around for many years, but over the last few years the interest in and use of such standards has risen quite dramatically, especially in the embedded space. This increased interest in certification and certified end products has been driven partly by legal demands, but it has also become a competitive factor for production companies to get the stamp of approval that a safety certification implies.

The international umbrella standard for many standards concerning functional safety is called IEC 61508 and came in a second, much revised edition in 2010. This standard, and standards derived from it, is now used within all kinds of industries with requirements on reliability and safety, such as process industries, railway, building automation etc. Within automotive systems, the sector-specific standard ISO 26262 is used. EN 50716 is a European standard for safety related software in railway applications and is also derived from IEC 61508. The international standard IEC 62304 is a standard which specifies life cycle requirements for the development of medical software and software within medical devices.

Validate and qualify

If you are about to start a project with safety-critical functionality or functional safety requirements, you are probably already aware that the tools you use must somehow be qualified as suitable for safety-related development. The exact requirements for how to qualify development tools differ depending on the standard you are working against and also to some extent the criticality of a malfunctioning product. It is also dependent on the nature of the tool; a compiler that produces code that goes into your product is trickier to qualify than a source code metrics tool, which in turn is trickier to qualify than a version control system or a requirements management system.

The various standards have different definitions of safety integrity, i.e. the level of criticality that is assigned to your product, and they also differ in exactly how tools are classified. For example, IEC 61508 states that a tool such as a compiler should preferably be certified, although it does not formally define what certified means. Further, it states that the tool should be validated as conforming to its specification or documentation. Worst case, this means that you would have to test the tool fully in your own project unless appropriate evidence of testing can be shown. Also, an assessment should be carried out to define the level of reliance placed in the tool.

Another thing that should be taken into account and assessed is the capacity of the tool provider to support the tools, preferably over the full life cycle of the safety-critical product.

Taking all this together can leave you with a rather large pile of work, and that is only for one tool and one project… This is the background for the certification of our toolchain.

Certified and validated!

What does the certification of our tools for use in safety-critical development really mean? It means that the amount of work you have to do to justify the use of the tools is drastically lessened because an independent third party, in this case TÜV SÜD, has made an assessment of our development activities, issue handling procedures and testing and verification activities and certifies that the tools live up to the requirements in IEC 61508, ISO 26262 and EN 50716, and for Arm, RX and RL78 also IEC 62304. This also means that if you choose C or C++ as a programming language, our toolchain is an excellent choice.

Prolonging life as we know it

So, if I select a certified tool, everything is well? Well… One thing that should be taken into account is the level of support you will need and the level of support you will get for the toolchain; this is not restricted to the duration of the project but includes the full life cycle of the product. It is not a given that a tool supplier will help you out if the tool is old and superseded by newer versions. The problem with that stance is that it is completely contrary to the needs of a typical safety-related project, where tool updates should be avoided as far as possible.

It is of no use to receive a bug fix for a previously qualified tool, if the update includes functional updates as well, as that will essentially require a re-qualification of the tool or an elaborate impact analysis of the changes as well as a testing effort.

By working for many years with customers developing safety-related software or services with high demands on availability, we have learned that the ability to provide support on "frozen" versions is very important. In this context, a frozen version is a tool version that is only subject to bug fixes and that never receives new features. Such a version can be kept alive and supported for as long as needed. In the past, we have tailored special agreements for customers in need of specific frozen versions and related support services. But with the certification, we have the opportunity to offer the frozen version concept and support to all customers using the Functional Safety edition of IAR Embedded Workbench, and we offer it in a streamlined over-the-counter package.

On and on and on

What do we provide in our safety offering? This is the offering in brief:

  • A special packaging of IAR Embedded Workbench for Functional Safety that includes the very specific version of the tools that are certified and frozen. This is available for Arm, RISC-V, STM8, RL78, RX and RH850.
  • A report to the certificate from TÜV SÜD stating under what circumstances the certificate is valid.
  • A safety guide, which in the terminology of various safety standards is a safety manual describing how the tool chain can be applied in safety-related development. The guide covers everything from things to consider when installing the tool chain, to how language extensions and compiler pragmas should be treated.
  • A Functional Safety Support and Update Agreement that includes support and pre-qualified bug fix updates to the certified version for as long as there are customers on the contract.
  • Regular updates on new known problems in the toolchain.

In short, selecting a certified build toolchain enables you to use it in your safety-related project with a minimum of fuss. Selecting a tool with appropriate support services included protects your tool selection and protects your investment in the tools. Further, the functional safety support services could be just as useful even if you are not under direct safety-related requirements, but your product is subject to various high-integrity or high-availability requirements.

Safety-Certified Tools Make the Difference

The combination of hardware with a known history, application software, diagnostic software, and safety-certified development tools is a powerful enabler for developers of safety-critical applications. It allows them to start development quickly and achieve end product certification efficiently, saving both time and money. This article examines the benefits of using a certified development and build chain.

Basics of Using the Preprocessor

Anyone who has ever read a piece of C source code has seen them—the preprocessor directives. For example, you can find include directives (#include) at the beginning of most source files. The preprocessor is a system that rewrites the source before the actual compiler sees it. Clearly, this is a very powerful tool—the downside is that you could accidentally shoot yourself in the foot.

In this article we will introduce the preprocessor and covered the basics, including object- and function-like macros, the include directive, conditional compilation, and end with the two special directives #error and #pragma.

Using C Standard Library Time and Clock Functions

In the C standard, there is a defined library on time and date declared in "time.h". The library is not limited to embedded applications, and widely used in order to obtain information about time and date. This library is supported by IAR Embedded Workbench, and in this article we will take a look at how to use it in the toolchain.

Features that are supported by time.h

The time and date library of the C language is defined in time.h. This header includes data types with respect to time, constants and functions:

The Benefits of Multicore Debugging

The IAR Embedded Workbench for Arm has the ability to debug multicore devices in a synchronized way. In this article you will learn more about multicore debugging in general and especially how IAR Embedded Workbench for Arm handles it.

Why multicore debugging?

Today, the demand for complex applications are increasing and it’s a clear trend that multicore devices are becoming more and more popular thanks to this. And as we all know “If we develop it, debugging will come”. By using multicore devices it’s possible to load balance, take advantage in different strength of different architectures, and it will possibly lower the product cost to have one multicore device rather than multiple devices.

Cross-Platform Build Tools for Arm | IAR

The IAR Build Tools for Arm are available with support for Linux (Ubuntu and Red Hat) and Windows. These tools offer leading code quality, outstanding optimizations for size and speed, and fast build times.

Supporting implementation in cross platform-based frameworks for automated application build and test processes, the tools enable large-scale deployments of critical software building and testing. This video gives a quick overview of the IAR Build Tools for Arm in action. More information is also available at the IAR embedded CI/CD solutions page.

Dealing With Non-Reentrant Functions in RTOS-Based Designs

This article is written by Jean J. Labrosse, RTOS Expert.

Reentrant vs Non-reentrant functions:

If shared functions only use local variables, they are generally reentrant (assuming the compiler itself generates reentrant code).  

Conversely, a non-reentrant function is one that uses one or more global variables to keep track of the state of the function. The online documentation for the IAR toolchain provides a list of non-reentrant functions as shown in Figure 1.


Figure 1,
List of non-reentrant functions provided bythe IAR STD library

A good example of a non-reentrant function can be found in the DLIB run-time C library, string.h: strtok().  This function is used to parse an ASCII string for “tokens”.  The description of strtok() from the IAR documentation is shown in Figure 2:

Figure 2, Description of strtok(), a non-reentrant function

  1. The simple (and partial) code example shown in Figure 3 shows the use of strtok(). ptoken is a pointer to the beginning of the next token (i.e. one of the animal names) extracted from string[].
  2. The first time you call strtok(), you specify the ASCII string to parse (i.e. string[]) and a list (could be more than one delimiter) of token delimiters, in this example: “,” (a single comma). The function returns as soon as it locates the first delimiter and replaces that delimiter in string[] with a NULstrtok() then positions an internal pointer at the next character (i.e. the next token) in string[].
  3. You must specify a NULL pointer (I used 0 in this case) as the first argument to the second (and subsequent) calls to strtok(). The second argument contains the token delimiter(s) which, by the way, could be different if you needed to look for other delimiting characters, but in this case, I kept the comma.
  4. Again, to extract the next token, you must specify a NULL pointer (I used 0 in this case) as the first argument to the second (and subsequent) calls to strtok(). The second argument contains the token delimiter(s).
  5. You continue passing the NULL pointer and the desired delimiter(s) until strtok() returns a NULL At that point, there are no more tokens in the string[].  
1)     char *ptoken;
char  string[80] = “Lion,Tiger,Panther”;

2)      ptoken = strtok(string, “,”);
ptoken contains “Lion”
The internal pointer points to the T in Tiger.

3)      ptoken = strtok(0, “,”);
   ptoken contains “Tiger”
The internal pointer points to the P in Panther.

4)      ptoken = strtok(0, “,”);
   ptoken contains “Panther”
   The internal pointer points to the NUL at the end of string[].

5)      ptoken = strtok(0, “,”);
   ptoken contains a NULL pointer because there are no more tokens

Figure 3, Invocation sequence of strtok()

Of course, you would implement strtok() in a loop if you are expecting many tokens.

Using Non-Reentrant functions in an RTOS application:

The whole point of the previous discussion is to emphasize the fact that strtok() (and other non-reentrant functions) keeps an internal pointer that keeps track of the next token.   

As a general rule, I recommend avoiding non-reentrant functions in an RTOS application. However, if you need the functionality provided by some non-reentrant functions, your RTOS application code needs to either:

  1. Implement a reentrant version of the desired non-reentrant function.
  2. ONLY use strtok() (and other non-reentrant functions) from one task. Although, each task can have its own non-reentrant function(s).
  3. A non-reentrant function is a shared resource that needs to be protected using mutex.

The pseudo-code snippet in Figure 4 shows how you would use a mutex to protect access to the non-reentrant function.

// Allocate storage for the mutex

// Initialize the mutex before any functions that uses strtok()


void  MyTask (void) 
{
    // Initialize task variables and I/Os as needed

    while (1) {
        // Wait for the event to wake up ‘MyTask’
        :
        :
        // Get string with tokens
        AcquireMutex(..);
        // Extract token(s) from desired string;
        ReleaseMutex(..);
        :
        :
    } 
}

Figure 4, Ensuring exclusive access to a non-reentrant function

Each task that uses strtok() would need to acquire/release the mutex as shown above.  Alternatively, you could implement a function (i.e. a service to your application code) that parses tokens into an array of tokens.  This function would hide the mutex implementation details and thus allow any task to extract tokens without having to worry about non-reentrancy.

Also note that I specified the use of a mutex because it avoids unbounded priority inversions which can happen if you were to use a semaphore.

SpeedCrunch 1.2.0 is out

It starts much faster on Windows, even with lots of saved tabs.

You can now set your own keyboard shortcuts and switch between Classic, Modern, and Hybrid looks in one step. You can also choose what happens when you launch SpeedCrunch while it’s already running: bring an open window forward, open a new one, or add a tab.

This release also fixes issues with unit calculations and number input, and adds a FAQ to the user manual.

Thanks to everyone who tried the pre-releases, made suggestions, reported bugs and sent feedback!

Download and read the full release notes.


SpeedCrunch 1.1 released

SpeedCrunch 1.1 is available for Windows, macOS, and Linux. This release brings new ways to work with sessions and constants, along with fixes for everyday editing and window behavior.

Private tabs let you work without automatically saving their calculations. Their contents are discarded when closed, and they are not restored on the next launch. You can also choose to open a private tab at startup or keep a private session as a saved one.

For those who prefer a more compact interface, Classic appearance options are available for the input area and keypad. Menus, panels, and the status bar can each follow either the system appearance or the selected SpeedCrunch theme.

Constant insertion is now searchable. Press Ctrl+Space, type a name or unit, and insert a result using the keyboard or mouse. The new nth-root function also handles negative values and quantities with units.

Several editing behaviors are configurable. You can disable automatic input adjustments, accept autocomplete suggestions with Enter, clear input with Escape, or use a steady cursor. Input digit grouping has also been restored.

The release fixes undo and redo, copy and paste, floating-panel restoration, and crashes while typing in long expressions. Other improvements include better input sizing across fonts, correctly positioned live previews, and clearer themed menu icons.

A portable macOS ZIP package is also available, keeping settings and sessions in a folder beside the app.

Download SpeedCrunch 1.1 and read the full changelog

Thank you to everyone who contributed code, reported problems, tested changes, or helped shape this release.

SpeedCrunch 1.0 released

SpeedCrunch 1.0

SpeedCrunch 1.0 is available now for Windows, with installer and portable ZIP packages, and for macOS, with an Apple Silicon-only DMG. We hope to have an official 1.0 package on Flathub soon for Linux users.

SpeedCrunch screenshot

Before upgrading: back up any sessions you want to keep.

This version introduces a completely new session system and file format, so sessions from previous releases won't be loaded. In your current version, use Session > Save to keep a backup, and Session > Export > Plain text to save a readable copy of your calculations. You can then recreate your sessions in 1.0 by pasting the expressions into the editor. See the session export instructions for details.

The unit syntax has also changed. Units now go in square brackets, for example 10[m], so expressions using the old syntax will need adjusting.

You can find a summary of the main changes since version 0.12, released in 2016, on the download page.

A few highlights:

  • Keep multiple sessions open across tabs, split panes and separate windows.
  • Sessions are saved automatically and easy to back up.
  • Edit an earlier calculation and recalculate all the expressions below it.
  • Work with lists and matrices, with new statistics and linear algebra functions.
  • Use a much improved unit system.
  • View results as fractions or in several formats at once.
  • Choose from more built-in themes or create your own.
  • A new logo.

This release includes many fixes and features requested over the past 10 years, but it isn't perfect, and development doesn't end here. As more people start using it, the community will no doubt find bugs and suggest improvements. The plan is to release new minor versions (1.1, 1.2, etc.) every 4 to 12 weeks, depending on the app's stability and demand for new features.

For developers and package maintainers: the official Git repository is now hosted on GitHub. The Bitbucket repository is obsolete.

Unfortunately, the entire issue tracking history was lost because Bitbucket did not give a final warning before shutting down its Issues platform. If you previously reported a bug or requested a feature that still needs attention, please submit it again on the GitHub issue tracker or any of our communication channels. Translation corrections are welcome too, as is feedback on any other part of the app.

Thank you to everyone who has contributed over the years, whether through code, translations, bug reports or suggestions.

How long does it take for an Item to become visible?

How long does it take for an Item to become visible?

Frames skipped counter in application_QML_Blog_Javier

Frames skipped counter in application

How long does it take for an Item that you’ve just loaded to become visible? Answering this question allows for a way to detect what some users would perceive as "frame drops". I write that in quotes because Qt Quick only draws frames when needed, meaning it doesn't drop frames; but it can show them later than one would expect. That is what we would like to identify: When components are drawn late, and by how many milliseconds or frames are they late?

I've come up with a simple solution - code below the article - on how to measure this. Items being measured must inherit a class based of QQuickItem that has a connection on QQuickItem::visibleChanged. Its visible property should be false by default. When visible becomes true, a slot will start measuring elapsed time and create a direct connection to QQuickWindow::afterFrameEnd. Once the scene graph has submitted a frame, the slot will take the measurement and disconnect the connection that triggered it to prevent further frames from triggering this event.

That alone isn't enough, however. If there were other elements on the scene being animated (say from the render thread via an Animator), those would trigger a frame swap before our item would have had a chance to be drawn, causing our measurement to be taken prematurely.
We need a way of knowing when the frame that draws our component is the one that got swapped into view. Enter QQuickItem::ensurePolished. Calling this function ensures that QQuickItem::updatePolish will be called when the scene graph is ready to render our item. We override QQuickItem::updatePolish and use it to set a flag that’ll tell us that the next frame to come be displayed will correspond to the component we’re measuring. Lastly, we read this flag during the next call to QQuickWindow::afterFrameEnd, effectively using it to trigger the elapsed time measurement only when our item is swapped onto the screen.

There is a variable amount of time between the last user interaction and the moment a frame can be rendered; because of that, a measurement in milliseconds is only accurate to the average time that it takes for one frame to be rendered immediately after the previous frame. That turns out to be 1 second divided by the display's refresh rate. We can use Qscreen::refreshRate, which gives us this value in hertz. For a 60hz display, a frame's time (T) would be 1000 ms / 60 hz ≃ 16 ms. Any time measured that is between zero and T (16 ms) would mean an instant frame swap. If we divide the measured time by T, and apply a floor function to the result, we get the number of frames dropped while making the component visible, which is a more consistent measurement than the number of milliseconds passed. For a well optimized program the output would be zero, one, or a positive integer very close to that. For more information about the rendering process, you can read scene graph and rendering from Qt's documentation.

Make C++ items visible during their instantiation, or they won’t show up on screen. This QQuickItem subclass is different from its parent in that the Item is not visible by default. We set visible to false from the C++ constructor because the order in which initial properties are evaluated and assigned in QML differs depending on the approach used to instantiate the Item and assign its initial properties. You may set the initial visible property of an item in QML to false, then make it true during its instantiation as a delegate somewhere, only for the QML Engine to optimally evaluate its initial value solely to true, causing the visibleChanged signal to never be emitted because there was, effectively, no change to the visible property. Setting the visibility to false from the constructor in C++ is a simple way to guarantee that visibleChanged will be triggered upon any initialization of the visible property in QML.

The code for the QQuickItem subclass described in this article is documented below. Hope you find it useful. Reach out to us if you need help profiling software, would like to receive our training courses, or need help developing tools such as this.

Best regards, Javier

Code

#include <QQuickItem>
#include <QQuickWindow>

class TimedItem : public QQuickItem
{
    Q_OBJECT
    QML_ELEMENT

    Q_PROPERTY(qint64 timeToDisplay READ timeToDisplay NOTIFY timeToDisplayChanged FINAL)

public:
    TimedItem(QQuickItem* parent = nullptr) : QQuickItem(parent),
              m_elapsedTimer(new QElapsedTimer())
{
    setVisible(false);
    // When made visible, measure time to display
    QObject::connect(this, &QQuickItem::visibleChanged, this, &TimedItem::startMeasuringTimeToDisplay, Qt::DirectConnection);
};

qint64 timeToDisplay() {
    return m_timeToDisplay;
};

signals:
    void timeToDisplayChanged();

private:
    void startMeasuringTimeToDisplay()
    {
        if (isVisible())
        {
            // Reset
            m_frameReady = false;
            // Attempt to take measurement after frame swaps
            QObject::connect(window(), &QQuickWindow::afterFrameEnd, this, &TimedItem::measure,
            static_cast<Qt::ConnectionType>(Qt::DirectConnection | Qt::UniqueConnection));
            // Force polish, ensuring elapsed measurement is taken on the right frame
            ensurePolished();
            // Take initial measurement
            m_elapsedTimer->start();
        }
    }

    void updatePolish()
    {
        // The frame for this component will be rendered after this
        m_frameReady = true;
    }

    void measure()
    {
        // This will be called for every frame until the right frame has been rendered
        if (m_frameReady)
        {
            // Measure elapsed time
            m_timeToDisplay = m_elapsedTimer->elapsed();
            // Prevent measuring further frame
            QObject::disconnect(window(), &QQuickWindow::afterFrameEnd, this, &TimedItem::measure);
            // Propagate measured time
            emit timeToDisplayChanged();
        }
    }

private:
    qint64 m_timeToDisplay = 0;
    QElapsedTimer *m_elapsedTimer;
    bool m_frameReady = false;
};

The post How long does it take for an Item to become visible? appeared first on KDAB.

From Prompt to QObject: Building an LLM-Powered Action Runtime for Qt Applications


From Prompt to QObject: Building an LLM-Powered Action Runtime for Qt Applications

TL;DR: this post presents an introspectable action runtime for AI-enabled Qt applications, where selected QObject instances are exposed through a smart-object registry, translated into a bounded planning context, and mutated through previewable, validated plans. The approach relies on Qt’s existing meta-object system, using Q_PROPERTY, Q_INVOKABLE, object registration, recursive type discovery, and structured operations to keep LLM-generated actions constrained to the actual runtime object graph. The Smart Shapes QML and C++ examples show promising results with both a self-hosted qwen3-coder:30b model and OpenAI’s gpt-5.4, while also exposing practical challenges around prompt refinement, context size, multi-action requests, operations versus JavaScript fallback, and domain-specific instructions. Future work points toward larger applications, stronger validation and permissions, better context management, and possibly a generic reflective MCP server for Qt applications.


Developing AI-enabled Qt applications often starts with a deceptively simple idea: let users describe what they want, then translate that intent into concrete changes in the running application. However, moving from a natural-language prompt to safe mutations over live QObject instances is not straightforward. The application needs to decide which objects are available, what properties and methods can be used, how to represent the intended changes before applying them, and how to keep LLM-generated output constrained to the actual runtime object graph. Given that, I&aposve been working on designing an introspectable action runtime for Qt applications: selected objects are exposed through a smart-object registry, an LLM provider turns user prompts into previewable plans, and an applier executes validated operations or controlled scripts against those objects. In this article, I’ll explore how these modules work together to transform prompts into structured, introspectable, and executable actions over Qt applications.

Given this, such action runtime platform should satisfy three key requirements:

  • First, it must be generic and non-intrusive enough to be applied to a wide range of Qt applications, regardless of whether the UI is implemented with Qt Widgets, Qt Quick, or a combination of both. This means the infrastructure should rely on Qt’s existing object model, meta-object information, properties, methods, and object ownership rules, instead of requiring application-specific adapters for every use case.
  • Second, it must be accurate when translating a user prompt into effective application behavior: natural-language requests should be converted into explicit, previewable, and validated plans that only reference exposed objects and supported operations.
  • Finally, performance should remain a first-class concern. The planning context sent to the provider must be rich enough to avoid ambiguous actions, but compact enough to keep latency under control, avoid unnecessary traversal of large object hierarchies, and preserve UI responsiveness while plans are generated and applied.

Architecture Overview

Figure 1 presents the major components of our introspectable action runtime platform.

From Prompt to QObject: Building an LLM-Powered Action Runtime for Qt ApplicationsFigure 1: main components of Qt Instrospectable Action Runtime platform

QSmartObjectRegistry is the bridge to the live Qt object graph. It exposes selected QObject instances, assigns stable references, and describes classes, properties, methods, and collections. QSmartObjectPlanner turns a prompt into a bounded planning context. It combines the user command with registry metadata, sends that context to a provider, and converts the response into a validated QSmartObjectPlan. QSmartObjectProvider is the AI backend abstraction. QLLMSmartObjectProvider is the concrete HTTP implementation, supporting OpenAI-compatible and Ollama-style chat endpoints. QSmartObjectPlan is the previewable contract between planning and execution. It stores the summary, confidence, issues, mode, structured operations, or fallback script. QSmartObjectApplier executes accepted plans. It either applies structured operations directly through Qt meta-object APIs or runs script fallback through QJSEngine. QSmartObjectExecution reports the final outcome, including success state, summary, errors, and script console output.

For an application to be endowed with an intelligent prompt, its relevant runtime state and behavior must be made visible through Qt’s meta-object system. In practice, this means modeling the objects that the prompt should control as QObject-derived classes, exposing editable state as Q_PROPERTY, and exposing safe actions as Q_INVOKABLE methods or slots (many Qt application are already implemented as such). Properties define what the system can inspect and mutate, while invokable functions define the operations that can be requested explicitly by the user. This is an important constraint: the prompt should not operate over arbitrary implementation details, but over a deliberate application surface that the developer decided to expose. The better this surface is named, typed, and organized, the more accurately a natural-language request can be translated into an effective application action.

Object registration and type discovery build on that exposed surface. The application registers selected live objects with QSmartObjectRegistry, optionally giving them stable semantic identifiers and human-readable labels. From there, the registry assigns internal references to these objects and uses Qt meta-object introspection to discover their readable and writable properties, invokable methods, class names, and QObject-based collections. This metadata becomes the planning context consumed by QSmartObjectPlanner: it tells the provider which objects exist, which types can be created or modified, and which operations are actually legal. In other words, registration selects the live objects that participate in prompting, while type discovery describes what the prompt is allowed to do with them.

Type discovery follows the QObject surface exposed by the application. Starting from the objects registered in QSmartObjectRegistry, the implementation inspects their meta-objects and recursively discovers QObject-derived types referenced by Q_PROPERTY declarations, including direct QObject* properties and supported QObject collections such as QObjectList or QList<T>. It also walks readable runtime property values to find live child objects and collection items, so the planning context can include not only the explicitly registered object, but also the relevant object graph reachable from it. This keeps discovery aligned with Qt’s meta-object system: arbitrary C++ implementation details remain hidden, while declared properties, invokable methods, and QObject relationships become available for planning. This enables registering central components, such as a Core object, which can end up registering all important objects in the application, such as controllers. Of course, developers can also define a more limited exposure model by individually registering only the desired objects or by turning off recursive type discovery.

Prompt Engineering

One of the main challenges in this approach is that a fully generic prompt can describe the mechanics of object discovery, planning, validation, and execution, but it cannot always capture the application’s domain semantics. The same property names and methods may have different meanings depending on the example, and some user requests require contextual rules that are not obvious from the meta-object data alone. For this reason, the generic smart-object prompt may be complemented by example-specific instructions. These instructions explain how the exposed objects should be interpreted in that particular application, which coordinate system is being used, how collections should be handled, which operations are preferred, and how ambiguous commands should be resolved. In practice, the generic prompt provides the execution contract, while the example-specific prompt gives the model the domain knowledge needed to produce accurate plans.

These are the most important fragments of currently adopted generic prompt:

You translate natural-language editing requests into a smart-object mutation plan. Return only a JSON object. Do not wrap it in markdown. The JSON object contains either structured operations or a JavaScript script that will run against live QObject wrappers. The planning context contains two authoritative sections: availableClasses and instances. Use availableClasses as an exhaustive class catalog for all exposed objects and QObject-derived member types, and instances for live objects, aliases, and collection membership. Prefer operations mode. Use script mode only when the request cannot be represented with the supported operation vocabulary.
...
Supported operations are setProperty, adjustProperty, callMethod, createObject, and destroyObject. Operation targets are direct object refs, created ids, or collection selections. Collection sources can use ownerRef for one owner, owner for a target resolving to one owner, or owners for a target resolving to many owners, including nested selection targets.
...
For setProperty and adjustProperty, the property field must exactly match a writable property listed in availableClasses for the target object&aposs class. For collection predicates, the predicate property must exactly match a readable property listed in availableClasses for the collection item class.
...
Treat the planning context as authoritative. Do not invent members that are not explicitly listed there.
...
If the request cannot be satisfied with the available classes, objects, properties, methods, or collection relations, do not approximate it. Return confidence 0.0, at least one issue, empty operations, and an empty script.
...
The result must have this structure: {"summary":"short summary","confidence":0.0,"issues":["optional issue"],"mode":"operations","operations":[{"op":"setProperty","target": {"type":"object","ref":"registry-ref"},"property":"propertyName","value":"value"}],"script":""}
...
For script fallback, set mode to script, operations to [], and script to the JavaScript statements. If the request is ambiguous, return an issue and the safest minimal plan.

Example Application

The current implementation includes both QML and C++ examples built around the same shape-editing scenario. In the QML example, the application uses the QtActionRuntime.SmartObjects QML API directly: shapes are created in a Qt Quick scene, exposed through SmartObjectRegistry, and controlled through LLMSmartObjectProvider, SmartObjectPlanner, and SmartObjectApplier objects declared from QML. The C++ example implements the same workflow with a Qt Widgets interface and a SmartObjectsDemoController, wiring the registry, provider, planner, and applier from C++ and reflecting the generated plan back into the UI before it is applied. Both examples expose shape objects with properties such as position, size, color, and type, then allow prompts like moving a circle or changing its color to be translated into validated smart-object plans, as described in Figure 2.

From Prompt to QObject: Building an LLM-Powered Action Runtime for Qt ApplicationsFigure 2: smart shapes example&aposs domain objects

Results

We tested the Smart Shapes example with both a self-hosted Ollama backend running qwen3-coder:30b and OpenAI’s gpt-5.4 model, and both produced good results for a range of natural-language commands. The prompts covered simple creation and editing requests, such as “create a new yellow circle”, “rename the yellow circle to myCircle”, and “move myCircle to the right of rectangleOne”, as well as destructive and spatial operations like “remove the red circle” and “arrange all circles evenly around rectangleOne, using a radius of 200 and the rectangle’s center as the arrangement center”. These tests helped validate that the exposed object model, generated planning context, and structured operation format were expressive enough for both local and hosted models to translate user intent into effective changes in the scene.

0:00
/0:13

Video 1: results for prompt "create a new yellow circle and a new purple circle in different positions"

The next step was to investigate object collection traversal and object discovery in more complex object graphs. The Smart Shapes example already exercises a simple collection through the scene’s list of shapes, but real applications usually expose deeper hierarchies: controllers own models, models expose collections, and collection items may reference other domain objects. The goal is to verify how well the planner can discover these relationships from registered root objects, follow QObject-valued properties and supported collections, and still generate accurate operations without requiring every object to be registered manually.

0:00
/0:13

Video 2: results for prompt "change yellow circle&aposs id to myCircle and position it to the right of circleTwo"

No example-specific instructions were required, so far, for this example because the exposed QObject properties and invokable methods already provided enough semantic information for the planner to generate accurate operations.

Next, we want to try prompts involving multiple objects and multiple actions in a single request. Simple commands are useful to validate the basic planning pipeline, but real user interaction will often combine several intentions at once, such as creating an object, positioning it relative to another one, changing its visual attributes, and updating its identifier in the same prompt. These scenarios are important because they test whether the planner can decompose a compound request into a complete sequence of operations, preserve the correct order of execution, and avoid summarizing changes that were not actually represented in the generated plan. At this point, qwen3-coder:30b occasionally started producing incorrect plans, while gpt-5.4 performed quite well.

0:00
/0:13

Video 3: results for prompt "move rectangleOne to (200, 200) and position all circles evenly distributed around the angles of a circle centered at rectangleOne and with a radius of 150"

Notice that the circles are not actually distributed around rectangleOne’s center. This happens because gpt-5.4 has no way to infer how shape centers are computed from the exposed properties alone. The issue was easily fixed by adding example-specific planning instructions, such as: “In this shape demo, x and y are top-left coordinates. Object centers are computed as (x + width / 2, y + height / 2)”.

Challenges and Future Work

The implementation also showed that the hard part is not simply calling an LLM, but defining a stable contract between the model and the Qt object graph. The implementation moved from an initial JavaScript-oriented approach to an “operations first, JavaScript after” architecture, then added asynchronous plan generation, cancellation, richer registry metadata, collection predicates, runtime property values, and several rounds of prompt refinement. Prompt design became a central concern because the model must not invent properties, confuse planning metadata with writable object properties, skip parts of multi-action requests, or summarize mutations that were not actually emitted.

Context window sizing is another practical issue: the planning context must include enough classes, instances, collection relations, and runtime values to make accurate decisions, but not so much that local models lose reliability or exceed their useful context. The operations mode gives a safer and more introspectable path for common mutations such as setting properties, calling methods, creating objects, destroying objects, and selecting collection items. JavaScript remains useful as a fallback, but it is harder to validate and has a larger execution surface. Other important challenges include handling provider differences between Ollama-style and OpenAI-compatible endpoints, validating JSON responses, resolving object references safely, and deciding how much of the live object graph should be exposed to the prompt.

A natural direction for future work is to package this infrastructure as a generic reflective MCP server for Qt applications. Instead of each application embedding its own prompt-to-object bridge, a Qt MCP layer could expose selected QObject instances, properties, invokable methods, object collections, and runtime state through a standard protocol, allowing external agents to inspect and operate on live Qt applications in a controlled way. Beyond that, there are several interesting extensions: better permission models for deciding which objects and operations are visible, richer schema generation for enums and value types, configurable recursive discovery policies, stronger plan validation before execution, undo/redo integration, transaction support for multi-step plans, visual plan previews, and model-independent test suites for comparing local and hosted providers.

Another promising direction is to improve context management, so large applications can expose only the subset of the object graph relevant to a given prompt while still preserving enough semantic information for accurate planning.

Last but not least, this solution must be tested in larger and more complex applications. The Smart Shapes example is useful because it makes the core ideas easy to see, but real Qt applications have deeper object graphs, richer domain rules, long-lived controllers, asynchronous operations, permissions, and state that changes while the user is interacting with the system. Those are the scenarios that will really test whether reflective discovery, bounded planning contexts, structured operations, and fallback scripting can scale beyond a controlled demo. If this approach continues to work there, it opens an interesting path: Qt applications that can expose their own runtime capabilities and let users interact with them through intent, not just through predefined UI controls. What about including API documentation, in a Retrieval-Augmented Generation (RAG)-like approach?

That’s all for now. Lots of fun happening over here. 😉

Singleton Controllers in Times of Declarative QML

Singleton Controllers in Times of Declarative QML

Controller objects have been the main way to glue your QML UI to your application's actual implementation of the I/O and business logic. However, over the years, the way to actually expose that controller object has changed. And now, we contributed a change in QQmlEngine that allows you to change it once again, and we believe: for the better.

What are "controllers" anyway?

Conceptually, controllers are a thin glue layer between your business logic and your QML, exposing the data that the GUI needs in a format it can easily use. They are implemented as QObject-derived instances, usually with properties exposing values that may or may not be writable, as well as potentially some Q_INVOKABLE methods that can be triggered by the QML and maybe some signals.

Usually, these controllers are specific to a single logical group of values and functions within the wider application. An application may have a hand-full to dozens of them for a big system. Models exposing collections of data are usually made available as read-only properties returning a QAbstractItemModel-derived data model on these controllers.

Often, these controllers need to be instantiated with some initialization, as they need references to the business-logic objects they expose to the GUI, listen for signals to get notifications of changes, etc. And that's where the trouble starts...

Pre-Qt 6

Context properties

In the early days of QML, one would often use controller instances exposed to QML as context properties. Doing that allowed one to instantiate the controllers under control of C++, giving it all the references the objects needed at that time. We would often expose them to QML using a naming pattern like starting the name with a double underscore __someController so that it was easy to recognize in the QML code. Using context properties however is no longer recommended. Their lookup is slow, and the QML compilers cannot reason about them, so code using them cannot be optimized. Nor is tooling available to help the QML programmer, as code completion and the likes are not possible.

Singleton Instances

Then came the qmlRegisterSingletonInstance method. This method allowed one to register a QML singleton, but it would return the instance that you passed it as an argument and that you could instantiate however you needed. That was a good solution, but it didn't have a long useful life as it didn't mesh well with the declarative registration and it had issues with the one instance being the instance for every QML engine in your application (if you had more than one).

Post-Qt 6

Since Qt 6, the recommended way to write QML is to create QML modules using declarative registration for C++-based objects. That has many benefits in terms of tooling and optimization, so it's good practice to do this. But it also meant that since Qt 6, one could no longer mix-and match imperative registration with declarative: you either used the one, or the other; which rendered the qmlRegisterSingletonInstance method above useless.

There are many possible approaches that I have seen being applied to still control the creation of controller objects, usually by registering a singleton that has a static create factory function and returning some C++ singletons there or something along those lines. That works, but isn't very elegant. An alternative approach is using initial properties on the root object, but that either requires accessessing the root id from other QML files or propagating the controllers all the way down the stack of items. Neither is a great solution for different reasons. My colleague Javier Cordero Pérez is making a couple of videos about ways to do this, so I won't go into detail here. These videos will be added here once they have been released.

New approach

That building this connection between C++ and QML was so inelegant - despite being so important - inspired me to finally take matters into my own hands and write a patch.

The result is available starting with Qt 6.12 onward and it combines the good things of qmlRegisterSingletonInstance and the declarative registration: you still register your controller type as a QML singleton so that the type is fully known by the tooling and access to it can be optimized. But we gain back the ability to provide a ready-made instance to the QML engine.

setExternalSingletonInstance

The API on QQmlEngine gained a single new method: QQmlEngine::setExternalSingletonInstance. It allows you to provide an instance of a type declared as a singleton as the instance to use in any QML running in that engine, just like you could with qmlRegisterSingletonInstance. In contrast to that old registration function, however, you call this method on your specific QQmlEngine instance. Note that the type has to be (declaratively) registered as a singleton type for this call to work. If you are using more than one engine, it is up to you to decide if you want to provide the same instance to these different engines, or have separate instances.

This simple method gives you back an elegant, supported way to fully control the instantiation of the QML singleton, and thus easily connect it to your business logic or whatever else you need to with it. However, it is up to you make sure that you do this call before any QML code actually tries to access the singleton. Otherwise, the engine will (try to) create it's own instance as it used to. You cannot replace an already existing singleton instance, so once there is one, it is the one.

It’s up to you to make sure that the provided singleton instance outlives the QML that depends on it. You can do that in any way that works in your context, but you could consider parenting the instance to the QQmlEngine instance, ordering the variables containing them on the stack correctly, or using QQmlEngine::setObjectOwnership to hand ownership of the singleton to the QML engine.

QML_UNCREATABLE for singletons

If you are providing your QML singleton instance yourself anyway, you logically also don't need it to be creatable by the engine either - although, it still can be, of course. If your controller type has a non-default constructor - perhaps to take in some references to your business logic instances - you can now mark your singleton with QML_UNCREATABLE, just like you can with other QML types. If you do that, you no longer need to supply a factory function (and even if you do, it won't be used).

Of course, if you mark a singleton as uncreatable, it is up to you to make sure you actually supply an instance via QQmlEngine::setExternalSingletonInstance before the singleton is needed from QML.

The post Singleton Controllers in Times of Declarative QML appeared first on KDAB.

Hotspot v1.6.0 released

by Editor Team (KDAB)

Hotspot v1.6.0 released

Hotspot is a standalone GUI designed to provide a user-friendly interface for analyzing performance data. It takes a perf.data file, parses and evaluates its contents, and presents the results in a visually appealing and easily understandable manner. Hotspot’s goal is to offer a modern alternative to perf report, making performance analysis on Linux systems more intuitive and efficient.

Version 1.6.0 introduces powerful new features, improved workflows, and numerous bug fixes to make profiling even smoother.

ChangeLog for Hotspot v1.6.0

This release focuses on usability improvements and extended analysis capabilities. The most notable additions are:

  • Support for archived perf files (e.g. perf.data.zip)
  • Regex filtering in the flamegraph
  • Tracepoint support
  • Various bug fixes and stability improvements

Open Archived perf Files Directly

Hotspot can now open perf recordings stored inside archives such as perf.data.zip.

This simplifies sharing profiling results, storing CI artifacts, and working with compressed recordings - no manual extraction required.

Regex in the Flamegraph

The Flamegraph view now supports regular expression filtering.

This makes it much easier to:

  • Match complex symbol patterns
  • Focus on specific subsystems or namespaces
  • Quickly narrow down large profiling datasets

Especially for large C++ codebases, regex search significantly speeds up navigation.

Hotspot_V1.6.0_Regex_Example

Regex in the flamegraph

Tracepoint Support

Hotspot 1.6.0 introduces support for tracepoints captured via perf.

This enables analysis of event-based data in addition to traditional sampling, giving deeper insight into system and runtime behavior.

Hotspot_V1.6.0_Tracepoints_Example

Tracepoints

Bug Fixes and Improvements

As usual, this release also includes numerous smaller fixes, UI refinements, and internal cleanups to improve overall stability and user experience.

For a complete overview of all changes, see the full changelog on GitHub.

Happy profiling!

Videos

Hotspot - A GUI for perf report:

Hotspot Demo from Embedded World 2022:

The post Hotspot v1.6.0 released appeared first on KDAB.

Automating Repetitive GUI Interactions in Embedded Development with Spix

Automating Repetitive GUI Interactions in Embedded Development with Spix

2023-07-05-18-08-38-small_Blog_Christoph_Spix

As Embedded Software Developers, we all know the pain: you make a code change, rebuild your project, restart the application - and then spend precious seconds repeating the same five clicks just to reach the screen you want to test. Add a login dialog on top of it, and suddenly those seconds turn into minutes. Multiply that by a hundred iterations per day, and it’s clear: this workflow is frustrating, error-prone, and a waste of valuable development time.

In this article, we’ll look at how to automate these repetitive steps using Spix, an open-source tool for GUI automation in Qt/QML applications. We’ll cover setup, usage scenarios, and how Spix can be integrated into your workflow to save hours of clicking, typing, and waiting.

The Problem: Click Fatigue in GUI Testing

Imagine this:

  • You start your application.
  • The login screen appears.
  • You enter your username and password.
  • You click "Login".
  • Only then do you finally reach the UI where you can verify whether your code changes worked.

This is fine the first few times - but if you’re doing it 100+ times a day, it becomes a serious bottleneck. While features like hot reload can help in some cases, they aren’t always applicable - especially when structural changes are involved or when you must work with "real" production data.

So, what’s the alternative?

The Solution: Automating GUI Input with Spix

Spix allows you to control your Qt/QML applications programmatically. Using scripts (typically Python), you can automatically:

  • Insert text into input fields
  • Click buttons
  • Wait for UI elements to appear
  • Take and compare screenshots

This means you can automate login steps, set up UI states consistently, and even extend your CI pipeline with visual testing. Unlike manual hot reload tweaks or hardcoding start screens, Spix provides an external, scriptable solution without altering your application logic.

Setting up Spix in Your Project

Getting Spix integrated requires a few straightforward steps:

1. Add Spix as a dependency

  • Typically done via a Git submodule into your project’s third-party folder.
git submodule add 3rdparty/spix git@github.com:faaxm/spix.git

2. Register Spix in CMake

  • Update your CMakeLists.txt with a find_package(Spix REQUIRED) call.
  • Because of CMake quirks, you may also need to manually specify the path to Spix’s CMake modules.
LIST(APPEND CMAKE_MODULE_PATH /home/christoph/KDAB/spix/cmake/modules)
find_package(Spix REQUIRED)
  • Add Spix to your target_link_libraries call.
target_link_libraries(myApp
  PRIVATE Qt6::Core
          Qt6::Quick 
          Qt6::SerialPort 
          Spix::Spix
)

4. Initialize Spix in your application

  • Include Spix headers in main.cpp.
  • Add some lines of boilerplate code:
    • Include the 2 Spix Headers (AnyRPCServer for Communication and QtQmlBot)
    • Start the Spix RPC server.
    • Create a Spix::QtQmlBot.
    • Run the test server on a specified port (e.g. 9000).
#include <Spix/AnyRpcServer.h>
#include <Spix/QtQmlBot.h>
[...]

//Start the actual Runner/Server
spix::AnyRpcServer server;
auto bot = new spix::QtQmlBot();
bot->runTestServer(server);

At this point, your application is "Spix-enabled". You can verify this by checking for the open port (e.g. localhost:9000).

Spix can be a Security Risk: Make sure to not expose Spix in any production environment, maybe only enable it for your Debug-builds.

Where Spix Shines

Once the setup is done, Spix can be used to automate repetitive tasks. Let’s look at two particularly useful examples:

1. Automating Logins with a Python Script

Instead of typing your credentials and clicking "Login" manually, you can write a simple Python script that:

  • Connects to the Spix server on localhost:9000
  • Inputs text into the userField and passwordField
  • Clicks the "Login" button (Items marked with "Quotes" are literal That-Specific-Text-Identifiers for Spix)
import xmlrpc.client

session = xmlrpc.client.ServerProxy('http://localhost:9000')

session.inputText('mainWindow/userField', 'christoph')
session.inputText('mainWindow/passwordField', 'secret') 
session.mouseClick('mainWindow/"Login"')

When executed, this script takes care of the entire login flow - no typing, no clicking, no wasted time. Better yet, you can check the script into your repository, so your whole team can reuse it.

For Development, Integration in Qt-Creator can be achieved with a Custom startup executable, that also starts this python script.

In a CI environment, this approach is particularly powerful, since you can ensure every test run starts from a clean state without relying on manual navigation.

2. Screenshot Comparison

Beyond input automation, Spix also supports taking screenshots. Combined with Python libraries like OpenCV or scikit-image, this opens up interesting possibilities for testing.

Example 1: Full-screen comparison

Take a screenshot of the main window and store it first:

import xmlrpc.client

session = xmlrpc.client.ServerProxy('http://localhost:9000')

[...]
session.takeScreenshot('mainWindow', '/tmp/screenshot.png')k

Now we can compare it with a reference image:

from skimage import io
from skimage.metrics import structural_similarity as ssim

screenshot1 = io.imread('/tmp/reference.png', as_gray=True)
screenshot2 = io.imread('/tmp/screenshot.png', as_gray=True)

ssim_index = ssim(screenshot1, screenshot2, data_range=screenshot1.max() - screenshot1.min())

threshold = 0.95

if ssim_index == 1.0: 
    print("The screenshots are a perfect match")
elif ssim_index >= threshold:
    print("The screenshots are similar, similarity: " + str(ssim_index * 100) + "%")
else:
    print("The screenshots are not similar at all, similarity: " + str(ssim_index * 100) + "%")

This is useful for catching unexpected regressions in visual layout.

Example 2: Finding differences in the same UI

Use OpenCV to highlight pixel-level differences between two screenshots—for instance, missing or misaligned elements:

import cv2

image1 = cv2.imread('/tmp/reference.png')
image2 = cv2.imread('/tmp/screenshot.png')

diff = cv2.absdiff(image1, image2)

# Convert the difference image to grayscale
gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)

# Threshold the grayscale image to get a binary image
_, thresh = cv2.threshold(gray, 30, 255, cv2.THRESH_BINARY)

contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(image1, contours, -1, (0, 0, 255), 2)

cv2.imshow('Difference Image', image1)
cv2.waitKey(0)

This form of visual regression testing can be integrated into your CI system. If the UI changes unintentionally, Spix can detect it and trigger an alert.

1024-637_Blog_Christoph_Spix

Defective Image

1024-639_Blog_Christoph_Spix

The script marked the defective parts of the image compared to the should-be image.

Recap

Spix is not a full-blown GUI testing framework like Squish, but it fills a useful niche for embedded developers who want to:

  • Save time on repetitive input (like logins).
  • Share reproducible setup scripts with colleagues.
  • Perform lightweight visual regression testing in CI.
  • Interact with their applications on embedded devices remotely.

While there are limitations (e.g. manual wait times, lack of deep synchronization with UI states), Spix provides a powerful and flexible way to automate everyday development tasks - without having to alter your application logic.

If you’re tired of clicking the same buttons all day, give Spix a try. It might just save you hours of time and frustration in your embedded development workflow.

The post Automating Repetitive GUI Interactions in Embedded Development with Spix appeared first on KDAB.

QFuture ❤️ C++ coroutines

Ever since C++20 introduced coroutine support, I was wondering how this could integrate with Qt. Apparently I wasn’t the only one: before long, QCoro popped up. A really cool library! But it doesn’t use the existing future and promise types in Qt; instead it introduces its own types and mechanisms to support coroutines. I kept wondering why no-one just made QFuture and QPromise compatible – it would certainly be a more lightweight wrapper then.

With a recent project at work being a gargantuan mess of QFuture::then() continuations (ever tried async looping constructs with continuations only? 🥴) I had enough of a reason to finally sit down and implement this myself. The result: https://gitlab.com/pumphaus/qawaitablefuture.

Example

#include <qawaitablefuture/qawaitablefuture.h>

QFuture<QByteArray> fetchUrl(const QUrl &url)
{
    QNetworkAccessManager nam;
    QNetworkRequest request(url);

    QNetworkReply *reply = nam.get(request);

    co_await QtFuture::connect(reply, &QNetworkReply::finished);
    reply->deleteLater();

    if (reply->error()) {
        throw std::runtime_error(reply->errorString().toStdString());
    }
    co_return reply->readAll();
}

It looks a lot like what you’d write with QCoro, but it all fits in a single header and uses native QFuture features to – for example – connect to a signal. It’s really just syntax sugar around QFuture::then(). Well, that, and a bit of effort to propagate cancellation and exceptions. Cancellation propagation works both ways: if you co_await a canceled QFuture, the “outer” QFuture of coroutine will be canceled as well. If you cancelChain() a suspended coroutine-backed QFuture, cancellation will be propagated into the currently awaited QFuture.

What’s especially neat: You can configure where your coroutine will be resumed with co_await continueOn(...). It supports the same arguments as QFuture::then(), so for example:

QFuture<void> SomeClass::someMember()
{
    co_await QAwaitableFuture::continueOn(this);
    co_await someLongRunningProcess();
    // Due to continueOn(this), if "this" is destroyed during someLongRunningProcess(),
    // the coroutine will be destroyed after the suspension point (-> outer QFuture will be canceled)
    // and you won't access a dangling reference here.
    co_return this->frobnicate();
}

QFuture<int> multithreadedProcess()
{
    co_await QAwaitableFuture::continueOn(QtFuture::Launch::Async);

    double result1 = co_await foo();
    // resumes on a free thread in the thread pool
    process(result1);

    double result2 = co_await bar(result1);
    // resumes on a free thread in the thread pool
    double result3 = transmogrify(result2);

    co_return co_await baz(result3);
}

See the docs for QFuture::then() for details.

Also, if you want to check the canceled flag or report progress, you can access the actual QPromise that’s backing the coroutine:

QFuture<int> heavyComputation()
{
    QPromise<int> &promise = co_await QAwaitableFuture::promise();
    promise.setProgressRange(0, 100);

    double result = 0;

    for (int i = 0; i < 100; ++i) {
        promise.setProgressValue(i);
        if (promise.isCanceled()) {
            co_return result;
        }
        frobnicationStep(&result, i);
    }
    co_return result;
} 

Outlook

I’m looking to upstream this. It’s too late for Qt 6.11 (already in feature freeze), but maybe 6.12? There have been some proposals for coroutine support on Qt’s Gerrit already, but none made it past the proof-of-concept stage. Hopefully this one will make it. Let’s see.

Otherwise, just use the single header from the qawaitablefuture repo. It an be included as a git submodule, or you just vendor the header as-is.

Happy hacking!

Caveat: GCC < 13

There was a nasty bug in GCC’s coroutine support: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=101367 It affects all GCC versions before 13.0.0 and effectively prevents you from writing co_await foo([&] { ... }); – i.e. you cannot await an expression involving a temporary lambda. You can rewrite this out as auto f = foo([&] { ... }); co_await f; and it will work. But there’s no warning at compile time. As soon as the lambda with captures is a temporary expression inside the co_await, it will crash and burn at runtime. Fixed with GCC13+, but took me a while to figure out why things went haywire on Ubuntu 22.04 (defaults to GCC11).