Quantcast
Channel: Planet Qt
Viewing all 15410 articles
Browse latest View live

KDAB on Qt: Using Visual Studio Code for Qt Applications – Part Two

$
0
0

In the last blog post we saw an essential, C++ oriented, Visual Studio Code setup. That was enough to get going right away, but we can still definitely do more and better. Here I’ll show you how to get a complete setup for your qmake and CMake projects, all this while also wearing a Qt hat (on top of my C++ hat) and having a deeper look at the Qt side.

Build qmake Qt projects

Qmake is not integrated with Visual Studio Code the way CMake is, so setting up a qmake project for build is slightly more convoluted than doing the same with CMake. This means we’ll have to define our own build tasks. We’re going to do this in two stages: build steps definition and build steps combination, leveraging the fact that Visual Studio Code implements task dependencies and ordered sequential execution of dependencies.

Create build steps

As far as build steps are concerned, the following are, in a nutshell, the ones that will cover most cases:

  • Create the build directory (in a way that doesn’t fail if the directory already exists)
    {
      "label": "Create build dir",
      "type": "shell",
      "command": "mkdir -Force path/to/build/dir"
    }
    

    Here, -Force is a powershell parameter that will prevent the command to fail if the directory already exists. On Unix based systems, you can use mkdir -p instead.

  • Run qmake
    {
      "label": "Run qmake",
      "type": "shell",
      "command": "qmake",
      "arg": [ ... add your qmake arguments here ... ],
      "options": {
        "cwd": "path/to/build/dir"
      }
    }
    
  • Run make/nmake/jom, depending on the platform
    {
      "label": "Run make",
      "type": "shell",
      "command": "jom",
      "options": {
        "cwd": "path/to/build/dir"
      }
    }
    
  • Clear build folder This can mean different things depending on how the build file is configured. It could be a simple make clean, or a more thorough removal of the whole content of the build folder.
    {
      "label": "Clear build folder",
      "type": "shell",
      "command": "jom clean",
      "options": {
        "cwd": "path/to/build/dir"
      }
    }
    
Combine build steps

Now that our steps are defined, we can go on and define the actual build tasks. We’ll prepare two for this example, one for running a build, and one for running a clean build. Let’s see the task for a regular build:

{
  "label": "Build",
  "dependsOn": [
    "Create build dir",
    "Run qmake",
    "Run make"
  ],
  "dependsOrder": "sequence"
}

There are two new properties here: "dependsOn" is a list of task labels, and it means that those tasks need to be executed before the current task is built, while "dependsOrder", when set to "sequence", will tell Visual Studio Code to run all dependent tasks sequentially and in the given order.

The task for a clean build is very similar and will only have an extra step where the project is cleaned before being built again:

{
  "label": "Clean build",
  "dependsOn": [
    "Clear build folder",
    "Create build dir",
    "Run qmake",
    "Run make"
  ],
  "dependsOrder": "sequence"
}

And that’s it, now it’s just a matter to open the command palette (Ctrl+Shift+P), select “Task: Run Task” and then “Build”.

Use a default task

As an alternative (or better, an addition) to selecting manually the build task from a list every time, Visual Studio Code also allows to run a default task with a key combination (Ctrl+Shift+B). To mark a task as default, you need to add a few extra lines to the task configuration:

{
  // ... task configuration
  "group": {
    "kind": "build",
    "isDefault": true
  }
}
Use your own Qt

If Qt is not configured at a system level, or you want to use a Qt version other than the default one installed and configured in your system, you need to explicitly configure the environment so that every task is run with the right Qt version in the path. Visual Studio Code allows you to do this every time a terminal is launched for running a task, so our environment customizations are set before running the task command.

This is done in the settings file (or in the workspace settings if you’re working with a workspace), and the property name for this setting is system dependent: either "terminal.integrated.env.windows", "terminal.integrated.env.linux", or "terminal.integrated.env.osx". The property requires an object, where each property is the name of an environment variable, and the associated value is the value for the variable. Below is an example configuration for Windows:

{
  // All other settings...
  "terminal.integrated.env.windows": {
    "PATH": "C:/Qt/5.12.4/msvc2017_64/bin;${env:PATH}"
  }
}

Build CMake Qt projects

Setting up a CMake based project using the CMake extension doesn’t require any settings manipulation if Qt is already configured on your system. What you will need is to select a CMake kit (the CMake extension finds them automatically), a build variant, and launch the build with F7.

Short video showing how to launch a CMake build with Visual Studio Code

However, you may want to use extra arguments in the configuration step or specify your build directory so for instance it doesn’t end up being inside the source directory. You can customize CMake configuration arguments by setting the property "cmake.configureSettings" in your settings file. This property expects a list of string arguments that will be passed to CMake during the configuration step:

"cmake.configureSettings": {
  "CMAKE_PREFIX_PATH": "my/prefix/path",
  "ENABLE_FEATURE": "1",
  "ENABLE_OTHER_FEATURE": "0"
}

To customize the build directory, just set "cmake.buildDirectory" to the desired path. This value may contain variables, so it can be configured, for instance, to point a path relative to the project folder:

"cmake.buildDirectory": "${workspaceFolder}/../build-cmake-project"

If you want to use a custom Qt version, or Qt is not configured system-wide (as is the case on Windows) it’s enough to set CMAKE_PREFIX_PATH properly in the "cmake.configureSettings" property in the settings file. For example:

"cmake.configureSettings": {
  "CMAKE_PREFIX_PATH": "otherprefixpath;C:/Qt/5.12.4/msvc2017_64"
  // ... other args
]

You can find a complete documentation for the CMake Tools extension here, featuring a guide on how to use CMake Tools from the UI, and a documentation for all available settings.

Running and debugging our Qt application

Now that your application has been built, let’s see how we can launch it and, most importantly, debug it.

Running qmake projects

For projects built with qmake, we don’t have any help from extensions and the only option we have is to bake our own launch configurations in the way we’ve seen in the last blog post. This is done in the launch configurations file (launch.json) or in the workspace file, and this is how a launch configuration looks:

{
  "name": "My application",
  "type": "cppvsdbg",
  "request": "launch",
  "program": "path/to/application",
  "stopAtEntry": false,
  "cwd": "${workspaceFolder}",
  "environment": [],
  "externalConsole": false
}

You can run launch configurations both with or without debugger, using “Debug: Start Debugging” (F5) or “Run: Start Without Debugging” (Ctrl+F5) respectively. If Qt is not configured at a system level, or you want to use a custom Qt version, the corresponding launch configuration will need to be explicitly configured to include Qt in its path.

You can do this by updating the "environment" property in the launch configuration. Below is an example for Windows, setting only the "PATH" environment variable. Configurations for other systems need to be adjusted but are essentially similar.

"environment": [
  {
    "name": "PATH",
    "value": "C:/Qt/5.12.4/msvc2017_64/bin;${env:PATH}"
  }
]

Side note: here ${env:PATH} means whaterever value the environment variable PATH has before the launch configuration is run. In general, the syntax ${env:VARNAME} can be used to get an environment variable in a task or a launch configuration.

Running CMake projects

Working with CMake is easier in principle, as the CMake extension provides the commands “CMake: Run Without Debugging” and “CMake: Debug”, allowing you to respectively launch and debug CMake targets.

However, this approach has a number of shortcomings:

  • It’s not possible to specify per-target run arguments for debug runs.
  • It’s not possible at all to specify run arguments for non-debug runs.
  • Some debugging options such as source mapping or custom views with natvis are not configurable using cmake settings.

So in conclusion using the CMake extension for running targets is not really convenient if you want a comprehensive debugging experience, and the best way to go is still to create your own launch configurations.

The CMake extension provides a few convenient variables for launch configurations:

  • ${command:cmake.launchTargetPath}: resolves to the full path of the executable for the target selected from the launch target menu.
  • ${command:cmake.launchTargetDirectory}: resolves to the directory containing the executable for the target selected from the launch target menu.

Qt aware debugging

What we’ve seen until now will let you build and run your Qt applications, using either your system provided Qt or your own. Debugging will work out of the box already, as long as the application code is involved. But wouldn’t it be great to also be able to peek inside Qt’s source code while debugging? Or if we had a better visualization for Qt specific types?

Turns out we can do both with little manipulation on launch configurations. Let’s see how.

Configure debug symbols

Usually Qt debug symbols are distributed alongside libraries, so there’s no real need to explicitly configure debug symbols paths. If that’s not the case, you can configure the debug symbols path by setting the "symbolSearchPath" property on a launch configuration. This property is a string and contains a list of paths separated by a semicolon.

"symbolSearchPath": "otherSearchPath;C:/Qt/5.12.4/msvc2017_64/bin"

This of course can be useful for adding debug symbols for other libraries too.

Source mapping

If the source directory for your Qt differs from the actual source directory (or directories) used while building it, you can configure the debugger to resolve those paths correctly. This happens for instance with binary Qt releases on Windows. You can enable source mapping in launch configurations by adding the "sourceFileMap" property. This property requires an object where each key is the source folder as it’s provided by the debug symbols, and the corresponding value is the path where the source code is in your system. This is how it can be configured for a binary Qt release on Windows:

"sourceFileMap": {
    "C:/work/build/qt5_workdir/w/s": "C:/Qt/5.12.4/Src",
    "Q:/qt5_workdir/w/s": "C:/Qt/5.12.4/Src",
    "C:/Users/qt/work/install": "C:/Qt/5.12.4/Src",
    "C:/Users/qt/work/qt": "C:/Qt/5.12.4/Src"
}
Using Natvis for Qt aware objects visualization

Natvis is a Visual Studio framework that allows you to customize how native C++ objects are visualized in the debugger. Natvis visualization rules are specified through xml files with a specific schema. A natvis file lists visualization rules for each C++ type, and every visualization rule consists in a series of properties. Such properties are meant to be user friendly and will be displayed on the debug window when visualizing objects of the corresponding type.

To name a few examples, a QString is visualized as the string it contains and has a size property and a number of items corresponding to its characters, and QRect will have a width and a height property instead of just the bare (and less intuitive) internal representation of the top left and bottom right points (x1, y1, x2, y2).

If you want to enable natvis in a debug run, just set the "visualizerFile" property in your launch configuration so that it points to the natvis file.

"visualizerFile": "path/to/qt5.natvis"

Debug pane before and after configuring natvis

You can find a ready to use natvis file for Qt 5 at this link.

Updating the code model

In order to be able to navigate Qt headers and enable IntelliSense for the Qt API, it’s enough to adjust the C++ settings for our project (c_cpp_properties.json) by adding the Qt include folder (and all its subfolders):

{
  // ...
  "includePath": [
    // ...
    "C:/Qt/5.12.4/msvc2017_64/include/**"
  ]
}

If you’re working on a CMake project, it’s also possible to use the CMake plugin as a configuration provider. Doing so, include paths and defines will be bound to the currently configured CMake build, and won’t need to be specified manually. This simplifies the C++ properties file considerably, as it’s shown in the example below:

{
  "configurations": [
    {
      "name": "Win32",
      "intelliSenseMode": "msvc-x64",
      "configurationProvider": "vector-of-bool.cmake-tools"
    }
  ],
  "version": 4
}

A note about using Visual Studio compilers on Windows

Visual Studio provides batch files that automate the environment setup necessary to use their C++ compiler and linker. In the last post we saw how it’s possible to configure a task so that it sets up the environment through the vcvars.bat script before running a command.

However, if you need to configure the environment with vcvars.bat for most of your build steps, it is also possible to configure Visual Studio Code so that it runs the batch file for every task. To do so, you need to tweak the configured shell (which is powershell by default on windows) and pass a few args. The setting name for doing this is “terminal.integrated.shellArgs.windows” and it’s set as follows:

"terminal.integrated.shellArgs.windows": [
  "Invoke-BatchFile 'C:/Program Files (x86)/Microsoft Visual Studio/2017/Professional/VC/Auxiliary/Build/vcvars64.bat' amd64",
  "; powershell"
]

What’s going on here is this: Visual Studio Code will launch by default every shell task by calling this command:

powershell  -Command 

So, if you set “terminal.integrated.shellArgs.windows” this way, the final command will look like this:

powershell Invoke-BatchFile 'path/to/vcvars' ; powershell -Command 

As a result, task commands will be effectively run in a powershell with the right environment set.

And that’s it for now. Many new things on the table, and some advanced features too. Hopefully this will help you with your workflow.

But there is still more to say, so make sure you don’t miss the next post!

About KDAB

If you like this blog and want to read similar articles, consider subscribing via our RSS feed.

Subscribe to KDAB TV for similar informative short video content.

KDAB provides market leading software consulting and development services and training in Qt, C++ and 3D/OpenGL. Contact us.

The post Using Visual Studio Code for Qt Applications – Part Two appeared first on KDAB.


KDAB on Qt: Kuesa 3D 1.2 release!

$
0
0

Today, KDAB is releasing version 1.2 of the 3D integration workflow Kuesa 3D, built on top of Qt 3D.

Kuesa™ 3D is a complete design-to-code workflow solution for 3D in real-time applications, centered around the open glTF™ 2 format, supported by Blender, Maya and 3ds Max.

Read the Press Release…

In short, Kuesa provides a workflow that simplifies work for both designers and developers. It is centered around the glTF 2 format. The idea behind Kuesa 3D is that changes made on 3D models shouldn’t require much, if any, work on the developer’s side. As a consequence, you can iterate more frequently, get feedback more often and release on time.

In this blog post, we will highlight some of the new features we have introduced. You can get the full details here.

What’s new since 1.1?

The Iro Material library

The glTF 2 format currently only supports a Metallic Roughness physically-based material. As a result, it looks great but can be very expensive to render and requires lots of assets. For many use cases, simpler materials can be used instead: this is what the Iro Material library offers.

The library provides several materials that simulate reflections, clear coats of paint or simple transparent surfaces. The benefits of Iro materials are twofold:

  • they significantly reduce your GPU usage (compared with PBR materials), making them ideal for embedded or mobile applications;
  • they offer a real WYSIWYG integration with your 3D authoring tool: Kuesa is going to render your 3D models exactly like they appear in your artists’ editing suite.

This video by my colleague Timo Buske shows Iro Materials in action:

Improved Blender Support

Despite a steep learning curve, Blender is a fantastic tool and the latest version brings lots of interesting features to the table. For that reason, we have added support for Blender 2.8.

We can therefore now rely on the official glTF 2.0 export bundled with Blender. Furthermore, to make the best use of it, we’ve contributed patches that allow extending the exporter through custom extensions.

Then, we’ve added an extension to allow exporting of Iro Materials to glTF 2.0 files. In addition, we’ve also updated the Kuesa Blender addon to show a real time preview of the Iro Materials in Blender. What you see in Blender is what you’ll get with Kuesa 3D.

Improved animation support

Currently, glTF 2.0 only supports animating transformation properties (translation, scale, rotation) of objects. Incidentally, there is a draft of an extension EXT_property_animation to add support to animate any property.

Since that was a really important feature for us, we’ve decided to implement it for Kuesa 3D. In that sense, we’ve added a custom EXT_property_animation to the exporter. Next, we’ve updated the glTF 2 importer in the Kuesa 3D Runtime library to parse it properly.

Hence, we can now animate material, lights or camera properties in Blender, export the scene as a glTF file (with the extensions) and load it with Kuesa 3D Runtime.

An updated offering

With this new release, we changed the offering of the product to satisfy different use-cases.

Kuesa 3D Studio

Kuesa 3D Studio is the complete solution a team can use in production, with everything needed to satisfy both designers and developers:

  • Kuesa 3D Design Plugins:
    • Blender addons supporting:
      • Kuesa 3D extensions for Layers and Iro materials
      • The EXT_property_animation extension
      • Real time preview of the Iro materials in the Eevee viewport
  • Kuesa 3D Tools:
    • glTF editor application allowing preview and introspection of glTF 2 scenes
    • collection of command line tools to check and optimize assets
  • Kuesa 3D Runtime: Qt module library on top of Qt 3D
    •  glTF 2.0 fully compliant loader
    • support of Kuesa 3D and EXT_property_animation extensions
    • retrieve the various resources held in the scene
    • playback animations
    • add post processing effects such as Bloom, Depth of Field …
    • use a premade Qt 3D FrameGraph

The Kuesa 3D Tools and Runtime also support any glTF 2.0 files coming from other application like Maya, 3DS Max or others, as long as they can export to glTF 2.0.

You can find out more about Kuesa 3D Studio here.

Kuesa 3D Runtime

Kuesa 3D Runtime is also available as a separate product, full support from us. The product is available on the Qt marketplace or directly from us. This is perfect if you want to try out Kuesa and see what you can do with it.

Like previous releases, it is freely available under the AGPL 3 license.

Since it is built on top of Qt 3D, you can use the full Qt 3D API to further customize your application. For the most part, you can leverage things like Picking, Camera handling and a lot more for free.

As for actual Qt requirements, Kuesa 3D Runtime requires either the latest Qt 5.12 or the new Qt 5.15 release.

Find out more about Kuesa 3D Runtime.

Additional Contributions

Lastly, Kuesa 3D is also a way for us to justify contributions to open source projects. In that sense, we’ve made a few contributions targeting:

  • Support for registering and creating user defined extension in Blender’s glTF exporter
  • Fixes for animations on the official Blender glTF exporter
  • Qt 3D bug fixes and performance improvements

Try it out!

You can download Kuesa 3D Runtime from our GitHub repository.

Download the latest Kuesa 3D Studio brochure.

Join our live webinars and ask questions:

Watch our Realtime Music Box short video where I explain all this running on one of our demos:

About KDAB

If you like this blog and want to read similar articles, consider subscribing via our RSS feed.

Subscribe to KDAB TV for similar informative short video content.

KDAB provides market leading software consulting and development services and training in Qt, C++ and 3D/OpenGL. Contact us.

The post Kuesa 3D 1.2 release! appeared first on KDAB.

KDAB on Qt: Kuesa 3D Studio 1.2 – Press Release

$
0
0

KUESA™ 3D Studio 1.2 released

A Complete Design-to-Code Workflow Solution for 3D Assets in Real-time Applications

  • version 1.2 released
  • makes 3D design and development workflows easy, fast and reliable
  • offers support for Maya, Autodesk 3ds Max, and Blender as well as any other glTF-compatible digital content creation tools
  • New: Iro materials library can simulate common surface properties with less designer and GPU overhead
  • free live webinar June 4th, 6pm CEST

Berlin, June 2nd 2020

Building software that is dependent on real-time 3D models – like for example an automotive dashboard, MRI machine, factory control system or furniture design tool – requires not only 3D designers and 3D programmers. It also demands the ability to bring these very different skill sets together into a smoothly operating workflow.

In conventional workflows, a massive problem is that the assets created by 3D artists can rarely be used by programmers directly, forcing the development team to hand-tweak models and hand-code animations to make things work. It also forces designers to move their designs to target hardware to see how they’ll actually appear. This manual work extends product release timelines, and the artificial wall it creates between 3D artists and software engineers is a bottleneck that prohibits rapid iteration and the fine-tuning required to develop fast and high-quality results.

To eliminate this problem KDAB created KUESA 3D Studio. It makes the collaboration of designers and developers much more manageable by offering a seamless, integrated workflow. Designers can realize their vision using their favorite tools, developers can focus on their strengths without having to deal with design issues, and management can rely on getting better products to market faster.

How does KUESA 3D Studio work?

KUESA 3D Studio is comprised of three main components.

The KUESA 3D Design Plugins augment a designer’s preferred digital content creation tools, allowing them to create and export fully accessible 3D scenes and to display content that visually matches the run-time environment.

Many additional utilities are integrated in KUESA 3D Tools for fine-tuning, conditioning, investigating, debugging, and optimizing 3D assets, usable by either designers or developers.

Libraries built on top of Qt and Qt 3D allow developers to integrate 3D scenes directly into applications. This module is called KUESA 3D Runtime.

What’s new in version 1.2?

One of the most significant improvements is the Iro Materials Library. Physically-based rendering (PBR) can generate amazing images, but not all embedded systems have enough processing power to handle it. Also, without knowing the actual physics, PBR isn’t easily tweakable to simulate materials such as a pre-defined bitmap that needs to appear glossy. For these cases, or any other where PBR may be overkill, KUESA 3D Studio supports the Iro Material Library. This library provides a catalog of materials that can simulate common surface properties (such as reflections, clear-coated paint, and transparency) and gives great looking results with less designer and GPU overhead.

By default, glTF™ only allows you to animate transformation properties like translation, rotation, scale. In lots of cases, it would be useful to animate other properties like material properties, camera properties etc. This has now been added through the use of a custom glTF extension.

An additional benefit is brought in by Qt 3D, which KUESA 3D Studio is based on and which is maintained by KDAB. With Qt 3D on Qt 5.15.0 very potent profiling capabilities have been added.

More features:

  • Support for Maya, Autodesk 3ds Max, and Blender, as well as any other glTF-compatible digital content creation tools
  • Ability to build 3D scenes with PBR, non-PBR, and node-based materials
  • Real-time performance on desktop and embedded systems
  • Integration of both 3D and 2D assets
  • Compressed textures, meshes, and images for faster load times, reduced application size, and optimal use of GPU resources
  • Full programmatic access to scene items with APIs in C++ and QML
  • Photo-realistic results consistent across design tools and applications
  • Special effects like bloom and depth-of-field
  • Up to date with Qt 3D performance improvements in Qt 5.15
  • Ability to incorporate tools into a continuous integration system resulting in consistent 3D asset verification and conditioning
  • Availability of AGPL 3 license for KUESA 3D Runtime

———————————————————————————————————————————

More information on www.kuesa.com

Live demo webinars are scheduled for:

June 4th 2020… (6pm Central European Time)

June 18th 2020... (8am Central European Time)

Video footage

About the KDAB Group

The KDAB Group is the world’s leading software consultancy for architecture, development and design of Qt, C++ and OpenGL applications across desktop, embedded and mobile platforms and is one of the biggest independent contributors to Qt. Our experts build run-times, mix native and web technologies, and solve hardware stack performance issues and porting problems for hundreds of customers, many among the Fortune 500. KDAB’s tools and extensive experience in creating, debugging, profiling and porting complex applications help developers worldwide to deliver successful projects. KDAB’s trainers, all full-time developers, provide market leading, hands-on, training for Qt, OpenGL and modern C++ in multiple languages. Founded in 1999, KDAB has offices throughout North America and Europe.

More Information on www.kdab.com Press Contact: press@kdab.com

Download this report

The post Kuesa 3D Studio 1.2 – Press Release appeared first on KDAB.

KDAB on Qt: QStringView Diaries: Zero-Allocation String Splitting

$
0
0

After four months of intensive development work, I am happy to announce that the first QStringTokenizer commits have landed in what will eventually become Qt 6.0. The docs should show up, soon.

While the version in Qt will be Qt 6-only, KDAB will release this tool for Qt 5 as part of its KDToolBox productivity suite. Yes, that means the code doesn’t require C++17 and works perfectly fine in pure C++11.

This is a good time to recapitulate what QStringTokenizer is all about.

QStringTokenizer: The Zero-Allocation String Splitter

Three years ago, when QStringView was first merged for Qt 5.10, I already wrote that we wouldn’t want to have a method like QString::split() on QStringView. QStringView is all about zero memory allocations, and split() returns an owning container of parts, say QVector, allocating memory.

So how do you return the result of string splitting, if not in a container? You take a cue from C++20’s std::ranges and implement a Lazy Sequence. A Lazy Sequence is like a container, except that it’s elements aren’t stored in memory, but calculated on the fly. That, in C++20 coroutine terms, is called a Generator.

So, QStringTokenizer is a Generator of tokens, and, apart from its inputs, holds only constant memory.

Here’s the example from 2017, now in executable form:

const QString s = ~~~;
for (QStringView line : QStringTokenizer{s, u'\n'})
    use(line);

Except, we beefed it up some:

const std::u16string s = ~~~;
for (QStringView line : QStringTokenizer{s, u'\n'})
    use(line);

Oh, and this also works now:

const QLatin1String s = ~~~;
for (QLatin1String line : QStringTokenizer{s, u'\n'})
    use(line);

QStringTokenizer: The Universal String Splitter

When I initially conceived QStringTokenizer in 2017, I thought it would just work on QStringView and that’d be it. But the last example clearly shows that it also supports splitting QLatin1String. How is that possible?

This is where C++17 comes in, on which Qt 6.0 will depend. C++17 brought us Class Template Argument Deduction (CTAD):

std::mutex m;
std::unique_lock lock(m); // not "std::unique_lock lock(m);"

And that’s what we used in the examples above. In reality, QStringTokenizer is a template, but the template arguments are deduced for you.

So, this is how QStringTokenizer splits QStrings as well as QLatin1Strings: in the first case, it’s QStringTokenizer, in the second, QStringTokenizer. But be warned: you should never, ever, explicitly specify the template arguments yourself, as you will likely get it wrong, because they’re subtle and non-intuitive. Just let the compiler do its job. Or, if you can’t rely on C++17, yet, you can use the factory function qTokenize():

const QLatin1String s = ~~~;
for (QLatin1String line : qTokenize(s, u'\n'))
    use(line);

QStringTokenizer: The Safe String Splitter

One thing I definitely wanted to avoid is dangling references a la QStringBuilder:

auto expr = QString::number(42) % " is the answer"; // decltype(expr) is QStringBuilder<~~~, ~~~>
QString s = expr; // oops, accessing the temporary return value of QString::number(), since deleted

The following must work:

for (QStringView line : QStringTokenizer{widget->text(), u'\n'})
    use(line);

But since the ranged for loop there is equivalent to

{
   auto&& __range = QStringTokenizer{widget->text(), u'\n'};
   auto __b = __range.begin(); // I know, this is not the full truth
   auto __e = __range.end();   // it's what happens for QStringTokenizer, though!
   for ( ; __b != __e; ++__b) {
     QStringView line = *__b;
     use(line);
   }
}

if QStringTokenizer simply operated on QStringView or QLatin1String, the following would happen: The __range variable keeps the QStringTokenizer object alive throughout the for loop (ok!), but the temporary returned from widget->text() would have been destroyed in line 3, even before we enter the for loop (oops).

This is not desirable, but what can we do against it? The solution is as simple as it is complex: detect temporaries and store them inside the tokenizer.

Yes, you heard that right: if you pass a temporary (“rvalue”) owning container to QStringTokenizer, the object will contain a copy (moved from the argument if possible) to extend the string’s lifetime to that of the QStringTokenizer itself.

Future

Now that we have developed the technique, we very strongly expect it to be used in Qt 6.0 for QStringBuilder, too.

By Qt 6.0, we expect QStringTokenizer to also handle the then-available QUtf8StringView as haystack and needle, as well as QRegularExpression and std::boyer_moore_searcher and std::boyer_moore_horspool_searcher as needles. We might also re-implement it as a C++20 coroutine on compilers that support them, depending on how much more performance we’ll get out of it.

Conclusion

QStringTokenizer splits strings, with zero memory allocations, universally, and safely. Get it for free right now from KDToolBox, and you can future-proof your code with an eye towards Qt 6.

About KDAB

If you like this blog and want to read similar articles, consider subscribing via our RSS feed.

Subscribe to KDAB TV for similar informative short video content.

KDAB provides market leading software consulting and development services and training in Qt, C++ and 3D/OpenGL. Contact us.

The post QStringView Diaries: Zero-Allocation String Splitting appeared first on KDAB.

KDAB on Qt: How to declare a qHash overload

$
0
0

Today’s blog post is about something that should be simple and apparently it causes trouble: how to declare a qHash overload for a custom datatype. This is necessary when we want to use custom datatypes as keys in a QHash. From the documentation:

A QHash’s key type has additional requirements other than being an assignable data type: it must provide operator==(), and there must also be a qHash() function in the type’s namespace that returns a hash value for an argument of the key’s type.

In other words, given a class like:

namespace NS {

class EXPORT MyClass
{
    A m_a;
    B m_b;
    C m_c; 
    D m_d;
    ~~~
};

}

How do we implement its qHash() overload? Let’s find out! (Most of this applies to std::hash too.)

Look at its operator==

The first thing to look at is the implementation of operator== (or operator<=>, coming C++20).

Assuming the implementation is sane, then the code will tell us which members are relevant for equality and which ones are not (caches, tags, whatever). The ones not relevant shall not be hashed (otherwise, you might end up with objects that compare equal and have different hashes).

If the type in question has a botched operator==, then either fix it if possible, otherwise kill the corresponding qHash() overload via = delete. This will avoid having people re-adding it in client code.

If the type does not have an operator==, or cannot have a meaningful one, do not provide qHash() at all.

What’s a “sane” implementation? Generally one that recursively uses plain operator== on the member subobjects. Fuzzy comparisons are a bad idea, making the type not hashable efficiently.

Prepare for Qt 6 (optional)

Optional step: prepare for some source-incompatible changes in Qt 6 (the impact is still unknown; possibly just warnings). Qt 6 changed the return type of qHash() from uint to size_t, so you can guard yourself with something like:

#if QT_VERSION < QT_VERSION(6, 0, 0)
using qhash_result_t = uint;
#else
using qhash_result_t = size_t;
#endif

Declaring your qHash overload

The idiomatic approach is:

namespace NS {

// 1. add a forward declaration for the class
class MyClass;

// 2. consume the forward declaration for the class, by
// forward declaring its qHash overload
EXPORT qhash_result_t qHash(const MyClass &c, qhash_result_t seed = 0) noexcept;

class EXPORT MyClass
{
    ~~~ // same as before
    
    // 3. add:
    friend EXPORT qhash_result_t qHash(const MyClass &c, qhash_result_t seed) noexcept;
};

}

The reason for going all the trouble with 1+2 is because friend declarations cannot have default parameters unless you’re also defining the function (cf. [dcl.fct.default]). Although QHash will never call your qHash overload without a seed, you may want to unit test it, call it from your own containers that aren’t seeded, etc.; so it’s just “polite” to have the second argument defaulted.)

In case your implementation is entirely inline, you can skip 1+2 and go just with 3, adding the default argument there, and defining (not just declaring) qHash in the body of the class. This would also make the qHash a hidden friend, which would be generally a good thing (see here, here and here for more information about hidden friends).

Using just 3 is not doable in general (e.g. if MyClass is pimpled), in which case your qHash must be out of line, so you have 1+2+3.

Whatever way you go, this will put your qHash overload in the surrounding namespace of your class, which is what you want (qHash is called via argument-dependent lookup in Qt).

Implementing your qHash overload

Then, implement it (inline or outline depending on MyClass). The idiomatic way to do so is to look at your operator==:

bool operator==(const MyClass &lhs, const MyClass &rhs) noexcept
{
    return 
        lhs.a == rhs.a &&
        lhs.b == rhs.b && ~~~;
}

Build your qHash exactly like it: on the same fields, in the same order. This explains why you want qHash to be a friend, just like operator==, to spare going through accessors:

qhash_result_t qHash(const MyClass &c, qhash_result_t seed) noexcept
{
    QtPrivate::QHashCombine hash;
   
    seed = hash(seed, c.a);
    seed = hash(seed, c.b);
    seed = hash(seed, c.c);
    ~~~
    return seed;
}

QtPrivate::QHashCombine is private API, but does not require any special buildsystem magic; it’s in , a public header.

The same result can be obtained with the convenience that I have added in Qt 6:

qhash_result_t qHash(const MyClass &c, qhash_result_t seed) noexcept
{
    return qHashMulti(seed, c.a, c.b, ~~~);
}

Reusing the same fields as operator==, in the same order, ensures the casual reader of the code that your hashing is correctly implemented.

If two objects are to be considered identical even if they have their data in a different order, then use QHashCombineCommutative / qHashMultiCommutative. For instance, you must use the commutative versions if you have a class that represents a set of elements, and two sets are equal if they have the same elements, even if stored in a different order. This again can be detected by looking at operator== and spotting a call to std::is_permutation or similar.

However, if your class simply uses a set, then in your operator== you will compare those sets via their own operator==, which means that hashing for your class will still use the non-commutative qHashMulti.

Things not to do in your qHash implementation

Summing

inline size_t qHash(const QQuickShapeGradientCacheKey &v, uint seed = 0)
{
    uint h = seed + v.spread;
    for (int i = 0; i < 3 && i < v.stops.count(); ++i)
        h += v.stops[i].second.rgba();
    return h;
}

A simple sum usually doesn’t spread different values apart enough for the hashing to be effective.

XORing

inline size_t qHash(const QV4Debugger::BreakPoint &b, uint seed = 0) Q_DECL_NOTHROW
{
    return qHash(b.fileName, seed) ^ b.lineNumber;
}

This cancels information out (the seed, the fields themselves).

Getting creative with magic numbers

inline size_t qHash(const QQuickPixmapKey &key)
{
    return qHash(*key.url) ^ (key.size->width()*7) ^ (key.size->height()*17) ^ (key.frame*23) ^
            (key.region->x()*29) ^ (key.region->y()*31) ^ (key.options.autoTransform() * 0x5c5c5c5c);
}

Completely “magic” prime sequence, raising many questions on the values used.

Being out of sync with your operator==

inline bool operator==(const QQuickPixmapKey &lhs, const QQuickPixmapKey &rhs)
{
    return *lhs.region == *rhs.region && *lhs.size == *rhs.size && *lhs.url == *rhs.url &&
            lhs.options == rhs.options && lhs.frame == rhs.frame;
}

This is the same datatype as the previous example. How can you know, from a quick glance, if the qHash overload is correct? (Not good, just correct; equal objects yield equal hashes.)

Creating lots of unnecessary copies/temporaries

size_t qHash(const QQuickTextNodeEngine::BinaryTreeNodeKey &key)
{
    return qHash(qMakePair(key.fontEngine, qMakePair(key.clipNode,
                                                     qMakePair(key.color, key.selectionState))));
}

This is because qMakePair copies. Not necessarily a big deal in case of small, trivially copiable types; but qHashMulti would just lead to cleaner code, and possibly spread the hashing more equally.

Hashing Qt datatypes for which Qt does not provide a qHash overload

All the above discussion refers to the case where the datatype is a user-defined one. Sometimes we may need to build a QHash using a Qt datatype as a key, and we find out that the data type does not have a qHash overload. What do we do in this case?

  1. Report a bug. Any Qt datatype that provides an operator== should also provide a qHash overload.
  2. Roll your own qHash, but protected by a Qt version check that blocks the usage of a higher version of Qt. That code must be revisited when Qt itself gets upgraded — if a new version introduces a qHash overload, your code may break in interesting ways (e.g. ODR violation).
  3. (“Worst case scenario”) Ditch QHash for std::unordered_map and a custom hasher (following the same reasoning of 1+2, you don’t want to specialize std::hash for Qt datatypes), or use a wrapper type.

Hashing std:: datatypes via qHash

Unfortunately, you really shouldn’t do it. First, it should be Qt’s job at providing hashers for datatypes defined by the Standard, not yours, so the previous point applies.

Second, it’s impossible to do it reliably, because a qHash overload for such datatypes should be declared in the std namespace, and that’s not allowed.

An overload in any other namespace will not work correctly. Given your rolled out qHash for an arbitrary std::foo datatype:

// not in namespace std
qhash_result_t qHash(const std::foo &foo, qhash_result_t seed = 0)
{
    return ~~~;
}

Then merely using a QHash will lull us into a false sense of security, as this code will work:

QHash h; 
h.insert(~~~, ~~~);

But many other usages will be, unfortunately, broken. Suppose you just use the datatype as a data member of a class:

struct MyStruct 
{
    std::foo m_a;
    int m_b;
    ~~~
};

And then you want to define its qHash overload just like we’ve seen before:

qhash_result_t qHash(const MyStruct &s, qhash_result_t seed = 0) 
{
    // (very likely) ERROR: qHashMulti does not find qHash(std::foo)
    return qHashMulti(seed, c.m_a, c.m_b); 
}

How is this possible? This is due to how ADL works, combined with 2-phase name lookup. Suppose that you have this little piece of code:

// calls f() on a T object
template  void call_f() { T t; f(t); }

struct S {};
void f(S);

void use() { call_f(); }

This code works, even if S and f(S) were declared aftercall_f(). This is what gives us the power of using qHashMulti (AKA call_f) that can use qHash overloads on arbitrary types (AKA f(S)), even if these overloads got introduced after qHashMulti‘s own definition.

If we change the code just slightly, however, we have a problem:

// same as before
template  void call_f() { T t; f(t); }

#include 
void f(std::foo);

void use() { call_f(); }

This code now does not compile (surprise!). The reason is that the call to f() inside call_f() will only look in some scopes:

  1. it will check if a f(std::foo) was declared beforecall_f() (it wasn’t)
  2. it will check for a f(std::foo) in std::foo‘s associated namespaces. Which is namespace std, not the one we’re in!

To make the example work, we would need to do something like this:

// same as before
template  void call_f() { T t; f(t); }

#include 
namespace std {
void f(foo);
}

void use() { call_f(); }

… which would be OK for just about any other namespace. Not for namespace std, though: as explained before, we are not allowed to declare an arbitrary new function in that namespace.

Moving the definition of f(std::foo) before call_f would work (this would mean defining our qHash(std::foo) before including the definition of qHashMulti). But if we do so, we lose the convenience of using qHashMulti (as well as qHash for any other fundamental type or Qt type!).

You can play with this code here on Godbolt.

Long story short: due to qHash design, it’s not possible to conveniently and reliably hash datatypes defined by the Standard. You can use workarounds, e.g. define wrapper types and use such types as keys in your QHash objects.

Bonus points

As in, nice things to have.

  • qHash overloads should really really be noexcept. Throwing from a hashing function sounds wrong on multiple levels.
  • qHash overloads are good candidates for being marked as pure functions, that is, functions that only read memory, never modify it (or have any visible side effects). Such markers should help the compiler optimizing the code further.Qt defines a couple of convenience macros for this. One is Q_DECL_PURE_FUNCTION, that means that the function only reads global memory. There’s also Q_DECL_CONST_FUNCTION, as a even more strict version: the function only reads the values of the parameters, not any memory at all. Note that passing a reference/pointer and reading through it makes a function PURE, not CONST (something like strlen is PURE). Use CONST with a qHash overload where you’d pass an argument by value because it’s a small trivially copiable type like QPoint, QVector3D or similar, otherwise use PURE.

Why do I bother with all this?

Because declaring “ordinary” hashing functions should be straightforward, unless you have profiling data to believe that you can do better than the idiomatic way. I keep seeing code that makes it look dark magic. It’s not!

Ideally, in some not-too-far future, we may reach a level where the compiler will autogenerate the hash function for us — just like in C++20 it may autogenerate the implementation of operator== for us!

Thanks for reading!

About KDAB

If you like this blog and want to read similar articles, consider subscribing via our RSS feed.

Subscribe to KDAB TV for similar informative short video content.

KDAB provides market leading software consulting and development services and training in Qt, C++ and 3D/OpenGL. Contact us.

The post How to declare a qHash overload appeared first on KDAB.

KDAB on Qt: Why is my screen dark

$
0
0

Part 3

If you are here from Part 1, you missed Part 2, somehow.

Black Screen

It’s a night scene

You have tried everything from the first two parts that seemed applicable, and your screen is still a window to the void? No problem: we’ve gathered another five reasons this could be happening and how to go about fixing them.

Issue 11: Is it a bird, is it a plane?

Your 3D environment (aka: scene) normally has several elements and those elements each have their own properties. One element of particular importance is ‘you’, the viewer of the scene. If you aren’t in a room, you can’t be expected to see what is in that room. With 3D scenes, the viewer is usually referred to as the camera. (Unlike in 2D where it’s often called a window or view)

Perspective View Frustrum

Wikibooks: Vertex Transformations

Part of the camera’s properties are the near and far clipping planes, which specify the closest point to the camera which is visible, and the furthest away point. Anything closer than the near plane, or further away than the far plane, will be clipped and hence invisible.

Of course, you can get something in between. If your cube is 200 units across, sitting at 900 units from the camera, and the far plane is at 1000 units … you will see half of it.

The solution here is to set the near and far plane distances appropriately to the scene you’re working in: sometimes this is easy, everything is a similar scale and stays a consistent distance to the camera. Other times, it’s a huge topic which requires redesigning your renderer to avoid  artefacts : especially when you have large distances or tiny objects. For more on this, and why selecting good near/far value is hard, read up ‘depth buffer precision’.


Issue 12: I just want to be normal.

When transforming surface normals, it’s important to use a correctly derived normal matrix (from your model and view transformations). If this normal matrix is incorrect, your normals will be incorrectly scaled or rotated, and this can break all the the corresponding lighting calculations.

(There’s many ways incorrectly loaded, transformed or generated normals can break lighting, more to come in a future part)

Technically you need to compute the transpose of the inverse of the upper 3×3 of your combined model-view matrix. Which is some slightly nasty mathematical juggling. Fortunately, QMatrix4x4 has a helper to compute the correct matrix for you. Just make sure to compute the normal matrix for any of your transformation matrices, and pass this into your shaders as an additional uniform value.


Issue 13: All the world’s a stage…

Ready, steady,… and? You have a beautifully crafted startup animation. There are fades, there’s camera movement, there’s a reflection map swooshing over the shiny surface of your model. Just remember to actually start the animation: in Qt, animations are not played on load (unlike some authoring tools), so maybe you just need to press ‘play’.


Issue 14: Triangels. Vertexes. Phong shading.

If you’re writing shaders by hand, and you have a misnaming of the attribute in your shader code, compared to the C++ or QML code which binds uniforms or attributes to those names, then most rendering languages will treat the unbound data as 0,0,0,0 in the shader. If it’s a colour, you’ll get black (if it’s a normal or vertex position, it’s likely also not what you want). The good news is the shading language doesn’t care about your spelling, it just cares that the names you use match. So you can happily use Triangels, so long as you call them that everywhere. (But it will break if someone helpfully fixes your code in one place and not the other…)

If you’re lucky, your graphics driver has a debug mode, or some developer tooling, to warn you when you set a name which is not used in the shader. However, there are various techniques which rely on unbound uniforms or attributes efficiently returning zeroes, so the default production driver is unlikely to warn you about this.


Issue 15: Primitive thoughts.

GPUs draw triangles. Lots of triangles, lovely triangles everywhere. But occasionally some old-timer with an SGI Indigo under their desk will mention some other stuff –fans and strips? Or quads? Or maybe you’re using tessellation shaders (they are great). All of these things are different primitive types, which tell the GPU what kind of thing we’re drawing. Even if you’re not using tessellation shaders (where you draw patches), drawing lines can be very useful in industrial and scientific models, and drawing points can be one way to draw many lights (think flying over a city at night) or clouds of particles.

But if you’re sending drawing commands yourself, you need to specify the primitive type: even if you’ve carefully arranged your geometry into buffers and arrays and indexes of beautiful triangles. And if the type is incorrect, you won’t see triangles, but maybe just points, which by default are single-fragment dots. Which can be really hard to see, or even invisible (depending on your lighting model and fragment shader)


There are many ways to mess up 3D rendering; new technologies, new languages, new engines are coming out everyday. If we helped you with your issue, or even more than one, great! However, if you are still having issues, we have more help on the way. Why not comment your issue below to possibly have it feature in one of the following parts?

About KDAB

If you like this blog and want to read similar articles, consider subscribing via our RSS feed.

Subscribe to KDAB TV for similar informative short video content.

KDAB provides market leading software consulting and development services and training in Qt, C++ and 3D/OpenGL. Contact us.

The post Why is my screen dark appeared first on KDAB.

qutebrowser development blog: Paving the road towards qutebrowser v2.0

$
0
0

Today, it's been exactly 6 months since I launched the GitHub Sponsors campaign - time flies!

I wanted to use this opportunity to update everyone on what has been going on, on my plans for qutebrowser's future, and on various other bits and bytes - I have a lot of things I …

pat26 MARGINALIA blog: Qt & Android: Setting wallpaper

$
0
0

Is your Android app written using Qt? Would you like to change the wallpaper on your Android device programmatically? Then join me in creating an Android app that generates and saves the image as wallpaper.


Using Qt Creator, create a new 'Qt Quick Application - Empty' naming it WallpaperExample.


Select both Desktop and Android Kits.  It is usually convenient to have a Desktop app to test non-Android features of the app.


Next, verify the WallpaperExample Desktop builds and runs.


Update main.qml so that it can used to set the wallpaper.


Create the AndroidManifest.xml. Additional changes to the XML will be neccessary later.
Select all the Android supported ABI's.


Now, verify the WallpaperExample Android builds and runs.


An effective  approach  for a Qt/QML/C++ app to perform Android specific tasks is to use Android's Java API. Android Java classes are accessible to a Qt application using the JNI convenience APIs in the Qt Android Extras module, such as QAndroidJniObject::callStaticObjectMethod.


Java classes in a Qt Android project need to maintain the Java naming conventions and the directory package structure.
The package name is the same package name assigned in the Android-Mainfest.xml.
Because this Java class, WallpaperGenerator,  requires access to application-specific resources, the Android Context must be passed in from QAndroidJniObject::callStaticMethod call in the Qt class.


The QAndroidJniObject::callStaticMethod calls the static method WallpaperGenerator.generateWallpaper which generates and sets the Android wallpaper on a seperate thread to prevent UI delay.










The method WallpaperGenerator.getWallpaper calls an image generating service and reads the response using common Java API. 
The method WallpaperGenerator.setWallpaper creates and sets the bitmap image using Android  specific API. 
An alternative to calling the methods getWallpaper and setWallpaper, the method generateWallpaper can be called.













AndroidManifest.xml requires a few changes before the app can run. Android requires the manifest.permission.SET_WALLPAPER permission. Starting with Android 9, API level 28, cleartext support is disabled by default and this app communicates with the wallpaper generating server using http, so usesCleartextTraffic must be enabled.


That's all it takes. Run the app and set wallpaper.



























Felgo: 13 Qt, QML and Felgo Tutorials & Resources for Beginners [2020]

$
0
0
If you’re new toFelgo or coding, then you’re most likely new to Qt and QML too. Qt and QML go hand in hand along with Felgo to help you make cross-platform apps and 2D games in just a few days. Although it’s the easiest way to make your app or game, if you’re just starting your coding journey, you might be struggling to get to grips with all the new info you need to take in.

Thankfully, there is lots of information online, QML and Qt tutorials, to help you out. Learn more about the differences between Felgo, QML, and Qt and take advantage of these tutorials and resources to boost your coding power.

Get Qt and QML consulting and training services from Felgo’s team if you need help with that. You can also outsource your Qt app development with Felgo.

The Differences between Qt, QML and Felgo

As a newcomer, you might have a lot of questions about the differences between these three terms. Qt, QML and Felgo are all separate entities but they all interact when you create your app or game with the Felgo SDK.

Qt is a cross-platform application framework. An application framework is the software that developers use to implement the standard structure of an application. Cross-platform refers to the fact that an application only needs to be written once but works on different systems. Therefore, your apps created with Qt can run on iOS, Android, Windows, and other systems, all without having to write separate codes for them! 

QML is a user interface markup language. A user interface markup language renders and describes graphical user interfaces and controls. QML is a part of the Qt framework. However, as QML was created initially for the rapid creation of UIs and animations, you can now use it for writing your app or game logic with a component-based approach. Also, you can mix JavaScript with QML easily and make any app or game you like with it.

Like Qt, Felgo is also a cross-platform application framework. The difference, however, is that Felgo adds a large number of components, elements, and other features to the existing Qt framework to make it even easier for developers to make their mobile apps and games. So we recommend using this slightly modified framework, as it speeds up development and reduces the amount of coding involved.

Looking for Qt Training, Consulting or Software Development?

The Best Qt Tutorials

1.      Getting Started with Felgo and Qt Creator

Now that you know the differences between the 3 terms, it’s time to get hands-on with them using a short QML tutorial. To start learning about Qt and Felgo, you’ll need to open up Qt Creator. This is a powerful IDE (Integrated Development Environment), available on all operating systems that will allow you to create cross-platform apps and games.

Qt Creator is included in your Felgo installation and you can learn how to set up your projects using an essential tutorial called Getting Started with Felgo and Qt Creator. This will guide you through the process of creating a new project and teach you a few simple rules of QML. This quick Qt tutorial is an absolute must for anyone learning Qt for the first time.

Download Felgo Now and Try These Helpful Qt & QML Tutorials Out For Yourself!

2.  Introduction to Qt – Qt Creator IDE Overview Tutorial

After you have completed the first Qt tutorial, this video will show you some more examples of just how powerful Qt Creator is. You will see the functionality of different parts of the framework and get more acquainted with the interface itself. Make sure to check out the Examples section on the Welcome tab within Qt Creator after you have downloaded Felgo. You will find a repertoire of amazing demos and possibilities with Qt, QML, and the Felgo SDK.

3.    Creating QML Objects

Once you know Qt Creator, you can start making your own app or game. The basic elements of any project made with Qt or Felgo are QML objects. QML objects include things like buttons, switches, etc. Learning how to implement these objects will help you throughout your coding career, so it’s important to understand them before going any further. Creating QML Objects is a great starting point for beginners, so make sure to check it out. This QML tutorial will teach you the absolute basics of coding with Qt and Felgo.

4.    Communication between QML Objects

For your app or game to have a level of functionality, your QML objects must be able to communicate with each other. Communication between QML Objects is a very user-friendly introduction to this subject and will teach you enough to start doing the really enjoyable stuff with your code. This is an essential part of coding both for apps and games, so definitely go through this Qt/QML tutorial.

5.    First Steps with QML

After completing the 3 previous tutorials, there are still a few more concepts to cover in order to gain a comprehensive understanding of Qt, QML and Felgo. The next tutorial to check out will go back over some of the same material covered in the previous tutorials but it will also expose you to some more essential Qt concepts. First Steps with QML is The Qt Company’s own essential getting started tutorial and isn’t to be missed. It brings you through setting up controls within apps and handling user input.

6. Entity Based Game Design

This is a fun tutorial that shows you how to make your first simple game. Entity Based Game Design teaches you to make a game by introducing you to entities and physics, two essential concepts to understand if you’d like to make mobile games. Once these are covered, you’ll also learn about particle effects, AI and how to use sounds in your games. This is a great tutorial if you’ve never made a game before because it only takes a quarter of an hour to complete.

7. C++ and Qt tutorial

This long playlist of YouTube videos might look dated, but is still one of the best Qt tutorials out there if you are looking to learn C++ and the Qt framework. Note, that these videos show you the workings of Qt 4, which has been replaced by Qt 5. Most of the code in these videos is still going to work however, but you might run into a few small problems. If you look on the bright side though, finding solutions to these issues will be a great development training for you. This is a good Qt tutorial for anyone wanting to develop in the Qt core framework, without any extra features and a simplified workflow.

8.   Felgo Tutorials for Apps and Games

Although they’re not strictly Qt tutorials, the Felgo tutorials teach you a lot about Qt for both game and app development. Compared to the previously mentioned videos, these tutorials use the Felgo framework, adding useful features and shortening development time. You’ll need to download Felgo or add it to your existing Qt installation to be able to follow these tutorials. The Felgo tutorials will teach you everything from making a simple Flappy Bird game to making your first functional app. And they also explain the most important Qt and QML features in an application-oriented way.

9.    Writing a Widget-Based Application with Qt 5

After you have completed some easier tutorials, you might want to jump straight into deeper waters. This long session on YouTube is a great resource to follow along, with detailed explanations of the processes under the hood in a Qt application. This is a Qt tutorial, which does not use any Felgo components. It’s definitely a good way to get an overview on Qt, before starting to use the extras Felgo has to offer.

Step-by-step guide to your first Android / iOS App

The Best Qt Resources

10.    Books

Not surprisingly, there are a bunch of books published on the subject of learning Qt. Although some of the books listed on the Qt Wiki have become a little outdated, Qt 5 Cadaques (alias the QML Book) by Juergen Bocklage-Ryannel and Johan Thelin is an excellent read for anyone learning Qt. It’s free to read online and has a great index so you can jump exactly to what you want to know. Juergen and Johan are passionate about coding with Qt so they’re a great influence for any newcomers out there. You can find many more books listed on The Qt Company’s website.

11.    Whitepapers

Even if you’re a beginner, the two whitepapers The Qt Company has published should be of interest to you. Beyond the Code and Driving the User Interface are free to download and cover two very diverse areas.

Beyond the Code is a great piece on how designers and programmers can work together to deliver successful Graphical User Interfaces for embedded systems. Driving the Automotive User Interface is a little different as it’s a review of the current trend of adding graphical center-consoles to cars. Check them out to get an idea of the range of projects that can be created with Qt, QML and Felgo.

12.    Demos and Examples

Demos and examples are a great way to learn how to make apps and games. Being able to look through other projects gives you insight into how different elements of a project are made and you can then copy them into your own applications. Look through the Felgo demos and examples to get a feel for what a finished game or mobile app project looks like. You can also have a look at the Qt demos.

You can also view all of the Felgo game examples and demos in the Felgo Sample Launcher. The Sample Launcher is a stand-alone desktop application that allows you to test all of the open-source demos and examples from Felgo quickly.

13.    Webinars

The Qt Company has released some great webinars over the years to help developers get to grips with certain topics. First and foremost, make sure to check out Get started with Qt. The other webinar that should be particularly useful to new developers is Introduction to Qt CreatorThis webinar is targeted at beginners and could be just the resource you need to get started. You can also download both of these and watch them later offline. Once you’ve watched them, you can move onto Deep Dive – Qt Quick & Qt Quick Controls or one of the other more in-depth webinars.

14.    Qt World Summit Talks

The Qt World Summit is an international event that takes place every year. Qt experts from around the world gather to share and discuss what they’ve learned about Qt in the previous 12 months and what they expect to learn in the coming years. Some of the videos are great for new learners as they include sample code that you can follow along with. These videos, in particular, are useful for newcomers:

Introduction to Qt Creator by Tobias Hunger

Getting Started with Qt on Android by BogDan Vatra

Qt on IOS A to Z by Mike Krus

The 8 Mistakes of QtQuick Newcomers by Luca Ottaviano, Develer

 

15.    Qt Quick Best Practices

Best Practices are basically a set of Do’s and Don’ts for developers to ensure that there is a certain quality to written code. The Best Practices are open to discussion and are usually decided on a group basis. You should always try to follow Best Practices if you’re releasing an app or game, or going to be working with others on a project. It’s a good thing to learn about these Best Practices when you start coding to avoid developing any bad habits which can be problematic down the road. This one is definitely for those that are serious about learning Qt.

16.    Qt Wiki Learning Portal

The Qt Wiki Learning Portal is the place to go to find even more learning resources. It’s a great collection of examples, demos, and resources for improving your Qt coding skills. Although a lot of the listings here are international language versions of other tutorials, there’s still something here for everyone.

Learn to Code with Qt and Felgo!

So now that you’ve got all of the tutorials and resources you need, go and learn to make something great with Qt. And if you find any other cool tutorials or resources, let us know and send us a direct message here.

More Posts like This

16 Great Sites Featuring Free Game Graphics for Developers

21 Tips That Will Improve Your User Acquisition Strategy

How to Download the Best Free Fonts for Mobile Development

16 Great Websites Featuring Free Game Sounds for Developers

 

References

Felgo: Meet Felgo at Qt Virtual Tech Con 2020!

$
0
0

Qt Virtual Tech Con 2020 is coming up in a couple of days and we’re already buzzing! The exhibition will be streaming live from the 12th-13th of May 2020.

This two-day virtual conference will provide a great opportunity to learn about the latest hot topics in Qt development. Get first-hand insights into creating high performing cross-platform applications. Qt Pros are sharing their best practices on how to design great UI & UX apps through videos, tutorials, interactive presentations, and dozens of Q&A and live sessions. 

We are excited to reconnect with our fellow software engineers again. Our CEO & Co-Founder, Chris, will share his insights about the best practices of mobile-optimized apps and the challenges you face before publishing them.

Francesc M. Qt Blog: New GitQlient release v1.1.0

$
0
0

I'm happy to announce the release of GitQlient 1.1.0

After two and a half months from the first release here I present a new release with some fixes, several improvements and new features. The main focus on this release was to improve the stability of GitQlient, making it faster on Windows (there is room for improvement still) and adding some big features that didn't go into the first release for time reasons.

New GitQlient release v1.1.0 first appeared on My C++ & Qt blog - Cesc M..

Felgo: Meet Felgo at Qt Virtual Tech Con 2020!

$
0
0

Discuss The Best Practices of Qt with Felgo at Qt Virtual Tech Con 2020!

Qt Virtual Tech Con 2020 is coming up in a couple of days and we’re already buzzing! The exhibition will be streaming live from the 12th-13th of May 2020.

This two-day virtual conference will provide a great opportunity to learn about the latest hot topics in Qt development. Get first-hand insights into creating high performing cross-platform applications. Qt Pros are sharing their best practices on how to design great UI & UX apps through videos, tutorials, interactive presentations, and dozens of Q&A and live sessions.

We are excited to reconnect with our fellow software engineers again. Our CEO & Co-Founder, Chris, will share his insights about the best practices of mobile-optimized apps and the challenges you face before publishing them.

Registering for The Event

You can select the session and set the reminder in your calendar during the online registration process. Don’t worry if you can’t make it as the talk will also be recorded and will be available on the Qt live event page.

Meet Our Speaker

Chris Feldbacher profilChris Feldbacher

 

Chris, the CEO & Co-Founder of Felgo, has vast experience in cross-platform app development with Qt and has also been a key speaker at many Qt conferences before. He also shared his expertise at Qt World Summit four times in a row and won the “Most Innovative Talk” award.

The Session Presented by Felgo in Detail:

Whether you’d like to bring your existing Qt application to mobile or develop your own mobile-optimized version, you will face many challenges before being able to publish it. In this talk, you will have the opportunity to deepen your knowledge and learn how to overcome mobile optimization challenges on iOS and Android.  Join us on May 12th 2020:

virtual

 

{{cta(‘9d99f958-08ad-481e-9340-3e0f5d03eb00′,’justifycenter’)}}

 

Recommended Articles

Our talented Qt developers carefully selected the best and most relevant Felgo articles to help you warm up for the conference.

Happy reading & happy coding!

Improve the Software Development Process with Qt

 

 

QML Tutorial: How to Create Native Cross Platform Apps with Qt and Felgo | Free Udemy Course

QML

Continuous Integration and Delivery (CI/CD) for Qt and Felgo

CI

 

Run your Qt and Felgo Apps in the Browser with WebAssembly (WASM)

WASM

 

The post Meet Felgo at Qt Virtual Tech Con 2020! appeared first on Felgo.

Qt – basysKom: Azure IoT Hub: Connecting a Qt Application with Azure (Part 1 of 4)

Cutelyst Framework: Cutelyst 2.11 and SimpleMail 2.1 released and a fork called Cutelee

$
0
0

Cutelyst the web framework based on Qt and SimpleMail the SMTP library got another update.

The current scenario has made me a lot less productive, after all 4 kids at home all the time it's really hard to concentrate. Still many fixes and a few features have landed both.

Simple mail had issues building on Windows, and also got some docs fixes.

Cutelyst got some Session parameters available on config, an WebSocket improvement to avoid setting a null body to skip RenderView processing, and a new view called Cutelee.

This year I got a big project, one that is pushing scalability on Cutelyst further, but it also requires that things progresses faster, and this means Grantlee was starting to become an issue. A while ago it's maintainer proposed to move it's code to KDE, got my hopes high, but that got postponed to Qt6, I couldn't wait for that and I also had an years old Pull Request waiting there, making in fact Cutelyst pages less safer as an escaping code wasn't escaping one special character. A Cutelyst contributor also had patches pending there, I tried my best to avoid this, the author is a great programmer, did an awesome job but we needed something that can move a little faster.

Cutelee was born, and already have many commits, it also got some performance improvements, like not converting QDate(Time) to an string and converting back to use the :date "yy/dd" formater, another important change was that it can inject filters without the hassle of creating a Qt Plugin, putting it into the right and error prone directory hierarchy, %with% tag also supports the new Django syntax, and I hope we can keep improving it at a faster rate.

I didn't do a new release of it yet, as some installation issues raised at Grantlee weren't fixed yet on Cutelee.

Have fun

https://github.com/cutelyst/cutelyst/releases/tag/v2.11.0

https://github.com/cutelyst/simple-mail/releases/tag/v2.1.0

https://github.com/cutelyst/cutelee

KDAB on Qt: Automating tasks in Qt Creator


KDAB on Qt: Using Modern CMake with Qt

$
0
0

KDAB’s Kevin Funk presented Using Modern CMake with Qt at Qt Virtual Tech Con last month.

He reported that the Qt Company did a great job moderating the sessions at this event, and there was a lively Q&A at the end – Kevin had to pick from about 60 questions, so this is a hot topic.

Now the event is over you can access Kevin’s talk here, including the answers he had time for, and also his slides, below the abstract.

Using Modern CMake with Qt with Kevin Funk

Prerequisite: No prior CMake experience required

CMake is a cross-platform build system, with powerful APIs for finding dependencies of various or specific versions, and with many abstractions for platforms, compilers, other build systems, and dependencies.

The next major Qt version, Qt6, will be using CMake internally as its build system, so the CMake integration with Qt will likely get tighter and more versatile in the long-term.

In this talk, we’ll be introducing Qt specific CMake functionalities, in order to find and use Qt5 inside your personal CMake-based project, using modern CMake capabilities. We are going to discuss how to find Qt installs using CMake’s find_package function and how to find specific Qt versions when multiple versions are installed.

Further than that, useful CMake variables such as CMAKE_INCLUDE_CURRENT_DIR, CMAKE_AUTOMOC, CMAKE_AUTORCC, and CMAKE_AUTOUIC will be explained in detail and how the use of the CMake integrations can speed up the build drastically.

Last but not least some of the additional supplied Qt related CMake functions, such as for big resources or translation support will be discussed.

Target audience: Build Engineers or Software Engineers who would like to know more about using Qt under CMake.

Download Kevin’s slides:QTVTC20 – Using Modern CMake – Kevin Funk

About Kevin Funk

Kevin has actively developed with Qt/C++ since 2006 and has a special interest in tooling and profiling. He’s an active contributor to KDAB’s GammaRay analyzer (a high-level Qt application debugger) and has a strong emphasis on state machine tooling. He is a co-maintainer of the KDevelop IDE, a powerful C/C++ development environment backed by Clang, and is pushing for cross-platform success inside KDE. Kevin holds a Masters Degree in Computer Science.

Download Kevin’s whitepaper on CMake and Qt…

The post Using Modern CMake with Qt appeared first on KDAB.

KDAB on Qt: Using Visual Studio Code for Qt Applications – Part Two

$
0
0

In the last blog post we saw an essential, C++ oriented, Visual Studio Code setup. That was enough to get going right away, but we can still definitely do more and better. Here I’ll show you how to get a complete setup for your qmake and CMake projects, all this while also wearing a Qt hat (on top of my C++ hat) and having a deeper look at the Qt side.

Build qmake Qt projects

Qmake is not integrated with Visual Studio Code the way CMake is, so setting up a qmake project for build is slightly more convoluted than doing the same with CMake. This means we’ll have to define our own build tasks. We’re going to do this in two stages: build steps definition and build steps combination, leveraging the fact that Visual Studio Code implements task dependencies and ordered sequential execution of dependencies.

Create build steps

As far as build steps are concerned, the following are, in a nutshell, the ones that will cover most cases:

  • Create the build directory (in a way that doesn’t fail if the directory already exists)
    {
      "label": "Create build dir",
      "type": "shell",
      "command": "mkdir -Force path/to/build/dir"
    }
    

    Here, -Force is a powershell parameter that will prevent the command to fail if the directory already exists. On Unix based systems, you can use mkdir -p instead.

  • Run qmake
    {
      "label": "Run qmake",
      "type": "shell",
      "command": "qmake",
      "arg": [ ... add your qmake arguments here ... ],
      "options": {
        "cwd": "path/to/build/dir"
      }
    }
    
  • Run make/nmake/jom, depending on the platform
    {
      "label": "Run make",
      "type": "shell",
      "command": "jom",
      "options": {
        "cwd": "path/to/build/dir"
      }
    }
    
  • Clear build folder This can mean different things depending on how the build file is configured. It could be a simple make clean, or a more thorough removal of the whole content of the build folder.
    {
      "label": "Clear build folder",
      "type": "shell",
      "command": "jom clean",
      "options": {
        "cwd": "path/to/build/dir"
      }
    }
    
Combine build steps

Now that our steps are defined, we can go on and define the actual build tasks. We’ll prepare two for this example, one for running a build, and one for running a clean build. Let’s see the task for a regular build:

{
  "label": "Build",
  "dependsOn": [
    "Create build dir",
    "Run qmake",
    "Run make"
  ],
  "dependsOrder": "sequence"
}

There are two new properties here: "dependsOn" is a list of task labels, and it means that those tasks need to be executed before the current task is built, while "dependsOrder", when set to "sequence", will tell Visual Studio Code to run all dependent tasks sequentially and in the given order.

The task for a clean build is very similar and will only have an extra step where the project is cleaned before being built again:

{
  "label": "Clean build",
  "dependsOn": [
    "Clear build folder",
    "Create build dir",
    "Run qmake",
    "Run make"
  ],
  "dependsOrder": "sequence"
}

And that’s it, now it’s just a matter to open the command palette (Ctrl+Shift+P), select “Task: Run Task” and then “Build”.

Use a default task

As an alternative (or better, an addition) to selecting manually the build task from a list every time, Visual Studio Code also allows to run a default task with a key combination (Ctrl+Shift+B). To mark a task as default, you need to add a few extra lines to the task configuration:

{
  // ... task configuration
  "group": {
    "kind": "build",
    "isDefault": true
  }
}
Use your own Qt

If Qt is not configured at a system level, or you want to use a Qt version other than the default one installed and configured in your system, you need to explicitly configure the environment so that every task is run with the right Qt version in the path. Visual Studio Code allows you to do this every time a terminal is launched for running a task, so our environment customizations are set before running the task command.

This is done in the settings file (or in the workspace settings if you’re working with a workspace), and the property name for this setting is system dependent: either "terminal.integrated.env.windows", "terminal.integrated.env.linux", or "terminal.integrated.env.osx". The property requires an object, where each property is the name of an environment variable, and the associated value is the value for the variable. Below is an example configuration for Windows:

{
  // All other settings...
  "terminal.integrated.env.windows": {
    "PATH": "C:/Qt/5.12.4/msvc2017_64/bin;${env:PATH}"
  }
}

Build CMake Qt projects

Setting up a CMake based project using the CMake extension doesn’t require any settings manipulation if Qt is already configured on your system. What you will need is to select a CMake kit (the CMake extension finds them automatically), a build variant, and launch the build with F7.

Short video showing how to launch a CMake build with Visual Studio Code

However, you may want to use extra arguments in the configuration step or specify your build directory so for instance it doesn’t end up being inside the source directory. You can customize CMake configuration arguments by setting the property "cmake.configureSettings" in your settings file. This property expects a list of string arguments that will be passed to CMake during the configuration step:

"cmake.configureSettings": {
  "CMAKE_PREFIX_PATH": "my/prefix/path",
  "ENABLE_FEATURE": "1",
  "ENABLE_OTHER_FEATURE": "0"
}

To customize the build directory, just set "cmake.buildDirectory" to the desired path. This value may contain variables, so it can be configured, for instance, to point a path relative to the project folder:

"cmake.buildDirectory": "${workspaceFolder}/../build-cmake-project"

If you want to use a custom Qt version, or Qt is not configured system-wide (as is the case on Windows) it’s enough to set CMAKE_PREFIX_PATH properly in the "cmake.configureSettings" property in the settings file. For example:

"cmake.configureSettings": {
  "CMAKE_PREFIX_PATH": "otherprefixpath;C:/Qt/5.12.4/msvc2017_64"
  // ... other args
]

You can find a complete documentation for the CMake Tools extension here, featuring a guide on how to use CMake Tools from the UI, and a documentation for all available settings.

Running and debugging our Qt application

Now that your application has been built, let’s see how we can launch it and, most importantly, debug it.

Running qmake projects

For projects built with qmake, we don’t have any help from extensions and the only option we have is to bake our own launch configurations in the way we’ve seen in the last blog post. This is done in the launch configurations file (launch.json) or in the workspace file, and this is how a launch configuration looks:

{
  "name": "My application",
  "type": "cppvsdbg",
  "request": "launch",
  "program": "path/to/application",
  "stopAtEntry": false,
  "cwd": "${workspaceFolder}",
  "environment": [],
  "externalConsole": false
}

You can run launch configurations both with or without debugger, using “Debug: Start Debugging” (F5) or “Run: Start Without Debugging” (Ctrl+F5) respectively. If Qt is not configured at a system level, or you want to use a custom Qt version, the corresponding launch configuration will need to be explicitly configured to include Qt in its path.

You can do this by updating the "environment" property in the launch configuration. Below is an example for Windows, setting only the "PATH" environment variable. Configurations for other systems need to be adjusted but are essentially similar.

"environment": [
  {
    "name": "PATH",
    "value": "C:/Qt/5.12.4/msvc2017_64/bin;${env:PATH}"
  }
]

Side note: here ${env:PATH} means whaterever value the environment variable PATH has before the launch configuration is run. In general, the syntax ${env:VARNAME} can be used to get an environment variable in a task or a launch configuration.

Running CMake projects

Working with CMake is easier in principle, as the CMake extension provides the commands “CMake: Run Without Debugging” and “CMake: Debug”, allowing you to respectively launch and debug CMake targets.

However, this approach has a number of shortcomings:

  • It’s not possible to specify per-target run arguments for debug runs.
  • It’s not possible at all to specify run arguments for non-debug runs.
  • Some debugging options such as source mapping or custom views with natvis are not configurable using cmake settings.

So in conclusion using the CMake extension for running targets is not really convenient if you want a comprehensive debugging experience, and the best way to go is still to create your own launch configurations.

The CMake extension provides a few convenient variables for launch configurations:

  • ${command:cmake.launchTargetPath}: resolves to the full path of the executable for the target selected from the launch target menu.
  • ${command:cmake.launchTargetDirectory}: resolves to the directory containing the executable for the target selected from the launch target menu.

Qt aware debugging

What we’ve seen until now will let you build and run your Qt applications, using either your system provided Qt or your own. Debugging will work out of the box already, as long as the application code is involved. But wouldn’t it be great to also be able to peek inside Qt’s source code while debugging? Or if we had a better visualization for Qt specific types?

Turns out we can do both with little manipulation on launch configurations. Let’s see how.

Configure debug symbols

Usually Qt debug symbols are distributed alongside libraries, so there’s no real need to explicitly configure debug symbols paths. If that’s not the case, you can configure the debug symbols path by setting the "symbolSearchPath" property on a launch configuration. This property is a string and contains a list of paths separated by a semicolon.

"symbolSearchPath": "otherSearchPath;C:/Qt/5.12.4/msvc2017_64/bin"

This of course can be useful for adding debug symbols for other libraries too.

Source mapping

If the source directory for your Qt differs from the actual source directory (or directories) used while building it, you can configure the debugger to resolve those paths correctly. This happens for instance with binary Qt releases on Windows. You can enable source mapping in launch configurations by adding the "sourceFileMap" property. This property requires an object where each key is the source folder as it’s provided by the debug symbols, and the corresponding value is the path where the source code is in your system. This is how it can be configured for a binary Qt release on Windows:

"sourceFileMap": {
    "C:/work/build/qt5_workdir/w/s": "C:/Qt/5.12.4/Src",
    "Q:/qt5_workdir/w/s": "C:/Qt/5.12.4/Src",
    "C:/Users/qt/work/install": "C:/Qt/5.12.4/Src",
    "C:/Users/qt/work/qt": "C:/Qt/5.12.4/Src"
}
Using Natvis for Qt aware objects visualization

Natvis is a Visual Studio framework that allows you to customize how native C++ objects are visualized in the debugger. Natvis visualization rules are specified through xml files with a specific schema. A natvis file lists visualization rules for each C++ type, and every visualization rule consists in a series of properties. Such properties are meant to be user friendly and will be displayed on the debug window when visualizing objects of the corresponding type.

To name a few examples, a QString is visualized as the string it contains and has a size property and a number of items corresponding to its characters, and QRect will have a width and a height property instead of just the bare (and less intuitive) internal representation of the top left and bottom right points (x1, y1, x2, y2).

If you want to enable natvis in a debug run, just set the "visualizerFile" property in your launch configuration so that it points to the natvis file.

"visualizerFile": "path/to/qt5.natvis"

Debug pane before and after configuring natvis

You can find a ready to use natvis file for Qt 5 at this link.

Updating the code model

In order to be able to navigate Qt headers and enable IntelliSense for the Qt API, it’s enough to adjust the C++ settings for our project (c_cpp_properties.json) by adding the Qt include folder (and all its subfolders):

{
  // ...
  "includePath": [
    // ...
    "C:/Qt/5.12.4/msvc2017_64/include/**"
  ]
}

If you’re working on a CMake project, it’s also possible to use the CMake plugin as a configuration provider. Doing so, include paths and defines will be bound to the currently configured CMake build, and won’t need to be specified manually. This simplifies the C++ properties file considerably, as it’s shown in the example below:

{
  "configurations": [
    {
      "name": "Win32",
      "intelliSenseMode": "msvc-x64",
      "configurationProvider": "vector-of-bool.cmake-tools"
    }
  ],
  "version": 4
}

A note about using Visual Studio compilers on Windows

Visual Studio provides batch files that automate the environment setup necessary to use their C++ compiler and linker. In the last post we saw how it’s possible to configure a task so that it sets up the environment through the vcvars.bat script before running a command.

However, if you need to configure the environment with vcvars.bat for most of your build steps, it is also possible to configure Visual Studio Code so that it runs the batch file for every task. To do so, you need to tweak the configured shell (which is powershell by default on windows) and pass a few args. The setting name for doing this is “terminal.integrated.shellArgs.windows” and it’s set as follows:

"terminal.integrated.shellArgs.windows": [
  "Invoke-BatchFile 'C:/Program Files (x86)/Microsoft Visual Studio/2017/Professional/VC/Auxiliary/Build/vcvars64.bat' amd64",
  "; powershell"
]

What’s going on here is this: Visual Studio Code will launch by default every shell task by calling this command:

powershell  -Command 

So, if you set “terminal.integrated.shellArgs.windows” this way, the final command will look like this:

powershell Invoke-BatchFile 'path/to/vcvars' ; powershell -Command 

As a result, task commands will be effectively run in a powershell with the right environment set.

And that’s it for now. Many new things on the table, and some advanced features too. Hopefully this will help you with your workflow.

But there is still more to say, so make sure you don’t miss the next post!

About KDAB

If you like this blog and want to read similar articles, consider subscribing via our RSS feed.

Subscribe to KDAB TV for similar informative short video content.

KDAB provides market leading software consulting and development services and training in Qt, C++ and 3D/OpenGL. Contact us.

The post Using Visual Studio Code for Qt Applications – Part Two appeared first on KDAB.

KDAB on Qt: Kuesa 3D 1.2 release!

$
0
0

Today, KDAB is releasing version 1.2 of the 3D integration workflow Kuesa 3D, built on top of Qt 3D.

Kuesa™ 3D is a complete design-to-code workflow solution for 3D in real-time applications, centered around the open glTF™ 2 format, supported by Blender, Maya and 3ds Max.

Read the Press Release…

In short, Kuesa provides a workflow that simplifies work for both designers and developers. It is centered around the glTF 2 format. The idea behind Kuesa 3D is that changes made on 3D models shouldn’t require much, if any, work on the developer’s side. As a consequence, you can iterate more frequently, get feedback more often and release on time.

In this blog post, we will highlight some of the new features we have introduced. You can get the full details here.

What’s new since 1.1?

The Iro Material library

The glTF 2 format currently only supports a Metallic Roughness physically-based material. As a result, it looks great but can be very expensive to render and requires lots of assets. For many use cases, simpler materials can be used instead: this is what the Iro Material library offers.

The library provides several materials that simulate reflections, clear coats of paint or simple transparent surfaces. The benefits of Iro materials are twofold:

  • they significantly reduce your GPU usage (compared with PBR materials), making them ideal for embedded or mobile applications;
  • they offer a real WYSIWYG integration with your 3D authoring tool: Kuesa is going to render your 3D models exactly like they appear in your artists’ editing suite.

This video by my colleague Timo Buske shows Iro Materials in action:

Improved Blender Support

Despite a steep learning curve, Blender is a fantastic tool and the latest version brings lots of interesting features to the table. For that reason, we have added support for Blender 2.8.

We can therefore now rely on the official glTF 2.0 export bundled with Blender. Furthermore, to make the best use of it, we’ve contributed patches that allow extending the exporter through custom extensions.

Then, we’ve added an extension to allow exporting of Iro Materials to glTF 2.0 files. In addition, we’ve also updated the Kuesa Blender addon to show a real time preview of the Iro Materials in Blender. What you see in Blender is what you’ll get with Kuesa 3D.

Improved animation support

Currently, glTF 2.0 only supports animating transformation properties (translation, scale, rotation) of objects. Incidentally, there is a draft of an extension EXT_property_animation to add support to animate any property.

Since that was a really important feature for us, we’ve decided to implement it for Kuesa 3D. In that sense, we’ve added a custom EXT_property_animation to the exporter. Next, we’ve updated the glTF 2 importer in the Kuesa 3D Runtime library to parse it properly.

Hence, we can now animate material, lights or camera properties in Blender, export the scene as a glTF file (with the extensions) and load it with Kuesa 3D Runtime.

An updated offering

With this new release, we changed the offering of the product to satisfy different use-cases.

Kuesa 3D Studio

Kuesa 3D Studio is the complete solution a team can use in production, with everything needed to satisfy both designers and developers:

  • Kuesa 3D Design Plugins:
    • Blender addons supporting:
      • Kuesa 3D extensions for Layers and Iro materials
      • The EXT_property_animation extension
      • Real time preview of the Iro materials in the Eevee viewport
  • Kuesa 3D Tools:
    • glTF editor application allowing preview and introspection of glTF 2 scenes
    • collection of command line tools to check and optimize assets
  • Kuesa 3D Runtime: Qt module library on top of Qt 3D
    •  glTF 2.0 fully compliant loader
    • support of Kuesa 3D and EXT_property_animation extensions
    • retrieve the various resources held in the scene
    • playback animations
    • add post processing effects such as Bloom, Depth of Field …
    • use a premade Qt 3D FrameGraph

The Kuesa 3D Tools and Runtime also support any glTF 2.0 files coming from other application like Maya, 3DS Max or others, as long as they can export to glTF 2.0.

You can find out more about Kuesa 3D Studio here.

Kuesa 3D Runtime

Kuesa 3D Runtime is also available as a separate product, full support from us. The product is available on the Qt marketplace or directly from us. This is perfect if you want to try out Kuesa and see what you can do with it.

Like previous releases, it is freely available under the AGPL 3 license.

Since it is built on top of Qt 3D, you can use the full Qt 3D API to further customize your application. For the most part, you can leverage things like Picking, Camera handling and a lot more for free.

As for actual Qt requirements, Kuesa 3D Runtime requires either the latest Qt 5.12 or the new Qt 5.15 release.

Find out more about Kuesa 3D Runtime.

Additional Contributions

Lastly, Kuesa 3D is also a way for us to justify contributions to open source projects. In that sense, we’ve made a few contributions targeting:

  • Support for registering and creating user defined extension in Blender’s glTF exporter
  • Fixes for animations on the official Blender glTF exporter
  • Qt 3D bug fixes and performance improvements

Try it out!

You can download Kuesa 3D Runtime from our GitHub repository.

Download the latest Kuesa 3D Studio brochure.

Join our live webinars and ask questions:

Watch our Realtime Music Box short video where I explain all this running on one of our demos:

About KDAB

If you like this blog and want to read similar articles, consider subscribing via our RSS feed.

Subscribe to KDAB TV for similar informative short video content.

KDAB provides market leading software consulting and development services and training in Qt, C++ and 3D/OpenGL. Contact us.

The post Kuesa 3D 1.2 release! appeared first on KDAB.

KDAB on Qt: Kuesa 3D Studio 1.2 – Press Release

$
0
0

KUESA™ 3D Studio 1.2 released

A Complete Design-to-Code Workflow Solution for 3D Assets in Real-time Applications

  • version 1.2 released
  • makes 3D design and development workflows easy, fast and reliable
  • offers support for Maya, Autodesk 3ds Max, and Blender as well as any other glTF-compatible digital content creation tools
  • New: Iro materials library can simulate common surface properties with less designer and GPU overhead
  • free live webinar June 4th, 6pm CEST

Berlin, June 2nd 2020

Building software that is dependent on real-time 3D models – like for example an automotive dashboard, MRI machine, factory control system or furniture design tool – requires not only 3D designers and 3D programmers. It also demands the ability to bring these very different skill sets together into a smoothly operating workflow.

In conventional workflows, a massive problem is that the assets created by 3D artists can rarely be used by programmers directly, forcing the development team to hand-tweak models and hand-code animations to make things work. It also forces designers to move their designs to target hardware to see how they’ll actually appear. This manual work extends product release timelines, and the artificial wall it creates between 3D artists and software engineers is a bottleneck that prohibits rapid iteration and the fine-tuning required to develop fast and high-quality results.

To eliminate this problem KDAB created KUESA 3D Studio. It makes the collaboration of designers and developers much more manageable by offering a seamless, integrated workflow. Designers can realize their vision using their favorite tools, developers can focus on their strengths without having to deal with design issues, and management can rely on getting better products to market faster.

How does KUESA 3D Studio work?

KUESA 3D Studio is comprised of three main components.

The KUESA 3D Design Plugins augment a designer’s preferred digital content creation tools, allowing them to create and export fully accessible 3D scenes and to display content that visually matches the run-time environment.

Many additional utilities are integrated in KUESA 3D Tools for fine-tuning, conditioning, investigating, debugging, and optimizing 3D assets, usable by either designers or developers.

Libraries built on top of Qt and Qt 3D allow developers to integrate 3D scenes directly into applications. This module is called KUESA 3D Runtime.

What’s new in version 1.2?

One of the most significant improvements is the Iro Materials Library. Physically-based rendering (PBR) can generate amazing images, but not all embedded systems have enough processing power to handle it. Also, without knowing the actual physics, PBR isn’t easily tweakable to simulate materials such as a pre-defined bitmap that needs to appear glossy. For these cases, or any other where PBR may be overkill, KUESA 3D Studio supports the Iro Material Library. This library provides a catalog of materials that can simulate common surface properties (such as reflections, clear-coated paint, and transparency) and gives great looking results with less designer and GPU overhead.

By default, glTF™ only allows you to animate transformation properties like translation, rotation, scale. In lots of cases, it would be useful to animate other properties like material properties, camera properties etc. This has now been added through the use of a custom glTF extension.

An additional benefit is brought in by Qt 3D, which KUESA 3D Studio is based on and which is maintained by KDAB. With Qt 3D on Qt 5.15.0 very potent profiling capabilities have been added.

More features:

  • Support for Maya, Autodesk 3ds Max, and Blender, as well as any other glTF-compatible digital content creation tools
  • Ability to build 3D scenes with PBR, non-PBR, and node-based materials
  • Real-time performance on desktop and embedded systems
  • Integration of both 3D and 2D assets
  • Compressed textures, meshes, and images for faster load times, reduced application size, and optimal use of GPU resources
  • Full programmatic access to scene items with APIs in C++ and QML
  • Photo-realistic results consistent across design tools and applications
  • Special effects like bloom and depth-of-field
  • Up to date with Qt 3D performance improvements in Qt 5.15
  • Ability to incorporate tools into a continuous integration system resulting in consistent 3D asset verification and conditioning
  • Availability of AGPL 3 license for KUESA 3D Runtime

———————————————————————————————————————————

More information on www.kuesa.com

Live demo webinars are scheduled for:

June 4th 2020… (6pm Central European Time)

June 18th 2020... (8am Central European Time)

Video footage

About the KDAB Group

The KDAB Group is the world’s leading software consultancy for architecture, development and design of Qt, C++ and OpenGL applications across desktop, embedded and mobile platforms and is one of the biggest independent contributors to Qt. Our experts build run-times, mix native and web technologies, and solve hardware stack performance issues and porting problems for hundreds of customers, many among the Fortune 500. KDAB’s tools and extensive experience in creating, debugging, profiling and porting complex applications help developers worldwide to deliver successful projects. KDAB’s trainers, all full-time developers, provide market leading, hands-on, training for Qt, OpenGL and modern C++ in multiple languages. Founded in 1999, KDAB has offices throughout North America and Europe.

More Information on www.kdab.com Press Contact: press@kdab.com

Download this report

The post Kuesa 3D Studio 1.2 – Press Release appeared first on KDAB.

KDAB on Qt: QStringView Diaries: Zero-Allocation String Splitting

$
0
0

After four months of intensive development work, I am happy to announce that the first QStringTokenizer commits have landed in what will eventually become Qt 6.0. The docs should show up, soon.

While the version in Qt will be Qt 6-only, KDAB will release this tool for Qt 5 as part of its KDToolBox productivity suite. Yes, that means the code doesn’t require C++17 and works perfectly fine in pure C++11.

This is a good time to recapitulate what QStringTokenizer is all about.

QStringTokenizer: The Zero-Allocation String Splitter

Three years ago, when QStringView was first merged for Qt 5.10, I already wrote that we wouldn’t want to have a method like QString::split() on QStringView. QStringView is all about zero memory allocations, and split() returns an owning container of parts, say QVector, allocating memory.

So how do you return the result of string splitting, if not in a container? You take a cue from C++20’s std::ranges and implement a Lazy Sequence. A Lazy Sequence is like a container, except that it’s elements aren’t stored in memory, but calculated on the fly. That, in C++20 coroutine terms, is called a Generator.

So, QStringTokenizer is a Generator of tokens, and, apart from its inputs, holds only constant memory.

Here’s the example from 2017, now in executable form:

const QString s = ~~~;
for (QStringView line : QStringTokenizer{s, u'\n'})
    use(line);

Except, we beefed it up some:

const std::u16string s = ~~~;
for (QStringView line : QStringTokenizer{s, u'\n'})
    use(line);

Oh, and this also works now:

const QLatin1String s = ~~~;
for (QLatin1String line : QStringTokenizer{s, u'\n'})
    use(line);

QStringTokenizer: The Universal String Splitter

When I initially conceived QStringTokenizer in 2017, I thought it would just work on QStringView and that’d be it. But the last example clearly shows that it also supports splitting QLatin1String. How is that possible?

This is where C++17 comes in, on which Qt 6.0 will depend. C++17 brought us Class Template Argument Deduction (CTAD):

std::mutex m;
std::unique_lock lock(m); // not "std::unique_lock lock(m);"

And that’s what we used in the examples above. In reality, QStringTokenizer is a template, but the template arguments are deduced for you.

So, this is how QStringTokenizer splits QStrings as well as QLatin1Strings: in the first case, it’s QStringTokenizer, in the second, QStringTokenizer. But be warned: you should never, ever, explicitly specify the template arguments yourself, as you will likely get it wrong, because they’re subtle and non-intuitive. Just let the compiler do its job. Or, if you can’t rely on C++17, yet, you can use the factory function qTokenize():

const QLatin1String s = ~~~;
for (QLatin1String line : qTokenize(s, u'\n'))
    use(line);

QStringTokenizer: The Safe String Splitter

One thing I definitely wanted to avoid is dangling references a la QStringBuilder:

auto expr = QString::number(42) % " is the answer"; // decltype(expr) is QStringBuilder<~~~, ~~~>
QString s = expr; // oops, accessing the temporary return value of QString::number(), since deleted

The following must work:

for (QStringView line : QStringTokenizer{widget->text(), u'\n'})
    use(line);

But since the ranged for loop there is equivalent to

{
   auto&& __range = QStringTokenizer{widget->text(), u'\n'};
   auto __b = __range.begin(); // I know, this is not the full truth
   auto __e = __range.end();   // it's what happens for QStringTokenizer, though!
   for ( ; __b != __e; ++__b) {
     QStringView line = *__b;
     use(line);
   }
}

if QStringTokenizer simply operated on QStringView or QLatin1String, the following would happen: The __range variable keeps the QStringTokenizer object alive throughout the for loop (ok!), but the temporary returned from widget->text() would have been destroyed in line 3, even before we enter the for loop (oops).

This is not desirable, but what can we do against it? The solution is as simple as it is complex: detect temporaries and store them inside the tokenizer.

Yes, you heard that right: if you pass a temporary (“rvalue”) owning container to QStringTokenizer, the object will contain a copy (moved from the argument if possible) to extend the string’s lifetime to that of the QStringTokenizer itself.

Future

Now that we have developed the technique, we very strongly expect it to be used in Qt 6.0 for QStringBuilder, too.

By Qt 6.0, we expect QStringTokenizer to also handle the then-available QUtf8StringView as haystack and needle, as well as QRegularExpression and std::boyer_moore_searcher and std::boyer_moore_horspool_searcher as needles. We might also re-implement it as a C++20 coroutine on compilers that support them, depending on how much more performance we’ll get out of it.

Conclusion

QStringTokenizer splits strings, with zero memory allocations, universally, and safely. Get it for free right now from KDToolBox, and you can future-proof your code with an eye towards Qt 6.

About KDAB

If you like this blog and want to read similar articles, consider subscribing via our RSS feed.

Subscribe to KDAB TV for similar informative short video content.

KDAB provides market leading software consulting and development services and training in Qt, C++ and 3D/OpenGL. Contact us.

The post QStringView Diaries: Zero-Allocation String Splitting appeared first on KDAB.

Viewing all 15410 articles
Browse latest View live