5

Beyond UI: Using Slint with C++

 4 months ago
source link: https://slint.dev/blog/beyond-ui-using-slint-with-cpp
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

December 8, 2023 by Miłosz Kosobucki (Guest post from KDAB)

Beyond UI: Using Slint with C++

We invited Miłosz Kosobucki to share his team's work at KDAB on how to implement non-UI functionality when writing a C++ application with Slint.


Most applications these days want to communicate over the internet or, in the case of embedded devices, report status over MQTT, for example.

If you're using Slint from C++, you've probably wondered: what should I use to implement these features that are beyond the UI? This is more relevant when the needed functionality requires asynchronous or blocking operations. After all, your application is driven by the Slint event loop:

int main(int argc, char **argv)
{
    auto ui = AppWindow::create();
    /*...*/
    ui->run();
    return 0;
}

Waiting on the HTTP response in the main thread would lead to the application's UI freezing.

Some possible solutions are:

auto curlMultiHandle = curl_multi_init();
//...
slint::Timer requestPollTimer(std::chrono::milliseconds(50), []{
    int runningHandles;
    CURLMCode mc = curl_multi_perform(curlMultiHandle, &runningHandles)
    //...
});
ui->run();
  • Move async operations to a separate thread and report results with slint::invoke_from_event_loop()

Unfortunately, none of the above options are ideal:

  • With polling, the application will have to wake up often to make sure that data transfers are handled in a timely manner. This is not good if you're targeting battery-powered devices.
  • With a separate thread you will need to handle the complexity of cross-thread communication. Your event loop in the secondary thread will have to wait for readiness of ongoing i/o operations and somehow wake up on signals from the main thread to initiate new transfers.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK