Skip to content

Monday, 17 March 2025

Welcome to the February 2025 development and community update.

Development Report

Text Tool Rework Update

Wolthera has written a new post about recent Text Tool updates which will be coming in Krita 5.3.

A Glyph Palette has been added to Text Tool Options, which allows selecting glyph alternates as well as showing a font character map (MR!2080). The Text Properties Docker now shows CSS Font Variants glyph properties (MR!2325) and OpenType features property (MR!2343).

Qt6 Port Progress

Krita now has Qt6 CI builds for Linux, Windows (MR!2328), and macOS (MR!2334). Android has yet to be built, as the platform has more complications and fewer developers working on it.

Most of Krita's custom Qt patches have now been ported by Dmitry, and ANGLE and HDR support are revived on Windows (deps commit).

Community Report

February 2025 Monthly Art Challenge Results

For the "Fabulous Flora" theme, 27 forum members submitted 34 original artworks. And the winner is… Hollyhocks by @Elixiah

Hollyhocks by @Elixiah

The March Art Challenge is Open Now

For the March Art Challenge, @Elixiah has chosen "Virtual Plein Air Painting" using MapCrunch or Google Maps street view, as the theme. The optional challenge is doing paired entries; one urban, one rural. See the full brief for more details, and see the sights without stepping outside your door.

Best of Krita-Artists - January/February 2025

Nine images were submitted to the Best of Krita-Artists Nominations thread, which was open from January 14th to February 11th. When the poll closed on February 14th, these five wonderful works made their way onto the Krita-Artists featured artwork banner:

Luca - To the Sea by @deerblue

Luca - To the Sea by @deerblue

Long Head Guy by @Celes

Long Head Guy by @Celes

Bird by @SkyJack

Bird by @SkyJack

Recent illustration I did for a card game by @JoaoGGarin

Recent illustration I did for a card game by @JoaoGGarin

Study of a Fox by @Hagetisse

Study of a Fox by @Hagetisse

Ways to Help Krita

Krita is Free and Open Source Software developed by an international team of sponsored developers and volunteer contributors.

Visit Krita's funding page to see how user donations keep development going, and explore a one-time or monthly contribution. Or check out more ways to Get Involved, from testing, coding, translating, and documentation writing, to just sharing your artwork made with Krita.

Other Notable Changes

Other notable changes in Krita's development builds from Feb. 12 - Mar. 17, 2025, that were not covered by the Development Report.

Stable branch (5.2.10-prealpha):

  • Resources: Correctly load UTF-8 .pat pattern names. (bug report) (Change, by Nicholas LaPointe)

Unstable branch (5.3.0-prealpha):

Bug fixes:

  • Animation: Fix crash on closing secondary animated document during playback. (bug report) (Change, by Emmet O'Neill)
  • General: Fix menubar disappearing after toggling system global menubar feature. (Change, by Carl Schwan)

Features:

  • Freehand Brush Tool: Add Brush Smoothing options to adjust the smoothing based on brushstroke speed. (Change, by killy |0veufOrever)
  • Preferences: Add a global pen tilt direction offset in Tablet settings. This can be used to make tilt brushes work similarly for left- and right-handed users, or behave better without tilt support. (Change, by Maciej Jesionowski)
  • Scripting: Add Canvas.setPreferredCenter() and Canvas.pan() for panning the canvas. (Change, by Dov Grobgeld)
  • Python Plugins: Add Mutator plugin. This consists of an action to randomly modify brush preset settings such as color and size, and a docker to customize these mutations. (Change, by Emmet O'Neill)
  • G'MIC: Update to 3.5.3. (Change, by Ivan Yossi)

Nightly Builds

Pre-release versions of Krita are built every day for testing new changes.

Get the latest bugfixes in Stable "Krita Plus" (5.2.10-prealpha): Linux - Windows - macOS (unsigned) - Android arm64-v8a - Android arm32-v7a - Android x86_64

Or test out the latest Experimental features in "Krita Next" (5.3.0-prealpha). Feedback and bug reports are appreciated!: Linux - Windows - macOS (unsigned) - Android arm64-v8a - Android arm32-v7a - Android x86_64

Sunday, 16 March 2025

I just got myself a brand new car: an ID.Buzz with seven seats so that I can fit the whole family at once. I’m very happy with the car this far, but since it has connectivity, I want to see if I can integrate it into HomeAssistant.

To do this, I wanted to use the CarConnectivity project by Till Steinbach. It is a Python package that comes in a few parts. The main project, a Volkswagen connector, an MQTT bridge and a HomeAssistant MQTT discovery helper.

Having played with the software for a bit (and reported a bug that Till fixed asap – I’m impressed!) I decided to setup the whole thing on my little RaspberryPi that runs a few little services I use around the house.

Preparing this, I setup a new user and installed the software in a Python virtual environment:

sudo adduser carconnectivity
sudo su carconnectivity
cd
mkdir carconnectivity
cd carconnectivity/
python -m venv venv
source venv/bin/activate
pip install carconnectivity-connector-volkswagen==0.5a1 carconnectivity-plugin-mqtt carconnectivity-plugin-mqtt_homeassistant
vim carconnectivity.json

Using the vim command, I created the CarConnectivity configuration file. Update usernames, passwords and IPs to your needs. I will experiment with the interval parameter, as I don’t want to discharge the 12v battery by querying the car too much.

{
        "carConnectivity": {
                "log_level": "error",
                "connectors": [
                        {
                                "type": "volkswagen",
                                "config": {
                                        "interval": 1800,
                                        "username": "hello@example.com",
                                        "password": "secret"
                                }
                        }
                ],
                "plugins": [
                        {
                                "type": "mqtt",
                                "config": {
                                        "broker": "my-mqtt.local",
                                        "username": "user",
                                        "password": "secret"
                                }
                        },
                        {
                                "type": "mqtt_homeassistant",
                                "config": {}
                        }
                ]
        }
}

Having configured the service (and having run it manually to fix my mistakes) I created the carconnectivity.service systemd service shown below (in /etc/systemd/system):

[Unit]
Description=Car Connectivity to MQTT
After=network-online.target

[Service]
Type=simple
User=carconnectivity
Group=carconnectivity
WorkingDirectory=/home/carconnectivity/carconnectivity/
Environment="LC_ALL=sv_SE"
ExecStart=/home/carconnectivity/carconnectivity/venv/bin/carconnectivity-mqtt /home/carconnectivity/carconnectivity/carconnectivity.json

[Install]
WantedBy=multi-user.target

And then I started and enabled the service.

sudo systemctl start carconnectivity
sudo systemctl enable carconnectivity

Finally, I had a look at the status and made sure that everything looks ok.

sudo systemctl status carconnectivity

And, viola, the car shows up as a device in Home Assistant. Magic!

Friendly country, Friendly people, Reunions, New Experience, a bit of hustle and that’s LIFE!

So, this was my 4th conference and 3rd international trip! A lot of new experiences and new friends, but let’s talk about FOSSASIA Summit 2025 first.

FOSSASIA Summit 2025

This is the first conference where I was having a lot of different tasks, lightning talk, representing Ubuntu booth and KDE booth. So, a lot of different perspectives will be here. Sometimes I’ll be writing from KDE’s pov, sometimes Ubuntu’s and sometimes my own.

Introduction

One of the biggest obstacles for users switching to Linux is choosing the right distribution. With the end of support for Windows 10 on October 14, 2025, many users are looking for alternatives to continue using their devices.
This project aims to help users migrate from Windows 10 to GNU/Linux by analyzing their system specifications, asking relevant questions, and recommending a ranked list of distributions with KDE Plasma based on their preferences.

This post will break down how we approached this problem in SoK25, focusing on two core challenges:

  1. Designing a recommendation logic that ranks distributions based on user preferences.
  2. Detecting hardware specifications and integrating them into the ranking logic.

Original Idea

Step 1: Initial Design for the Questionnaire

When we started the project, we considered including a range of distributions and desktop environments. Over the course of SoK, however, we decided to limit the recommendations to distributions offering KDE Plasma. I will first present the original idea.

To keep things simple, we decided to limit the number of questions we would ask Windows users. Instead of overwhelming users with technical details, we settled on a set of key questions. These cover parameters like:

  • Ease of installation
  • Support for older hardware
  • Quality of documentation
  • Community support
  • Frequency of updates (Rolling or Point)
  • Preferred UI style (Windows-like or Mac-like)

Each response contributes to a “parameter” of user preference vector, which helps in matching the needs of user with the best-fitting distributions.

Step 2: Selecting Initial Distributions

We initially started with a limited set of well-known beginner-friendly distributions:

  • Fedora KDE
  • Kubuntu
  • Lubuntu
  • Linux Mint XFCE
  • Linux Mint Cinnamon

Revised Idea

Over the course of SoK25 we decided to narrow the scope of the chooser app and rename it Win10-2-KDE-Chooser. After receiving some feedback from the community, we decided it made sense to focus on KDE-only solutions for a Season of KDE project, while others can adapt the idea at a later date.
With this new scope, we think the app can be promoted by the KDE community in the context of the ‘End Of 10’ campaign. The new scope includes:

  • The app will target devices running Windows 10.
  • The app will recommend distros with KDE Plasma.
  • The recommended distros for first-time users include Fedora KDE, Kubuntu, and Debian KDE (specifically the live installer, which uses Calamares).

In the rest of this SoK25 post, I will describe the implementation of the original idea in more detail, and this can later be adapted before release. This has been the focus of my work for the first half of SoK25.

Step 3: The Recommendation Logic

The core logic behind ranking distributions is vector-based similarity measurement. Each distribution is represented as a vector, with dimensions corresponding to the parameters defined in our questionnaire.

The approach works as follows:

  1. User Preference Vector: The answers provided by the user form a vector with numerical values assigned to each preference.
  2. Predefined Distribution Vectors: Each distribution has a corresponding vector based on predefined scores.
  3. Similarity Calculation: The similarity between the user vector and each distribution vector is computed using a mathematical function.

TL;DR : We are using dot product and a penalty criteria (multiplying by 0.5) for ranking the distros

Choosing the Right Similarity Function

Initially, we considered cosine similarity, but we found that dot product gave better results.

  • Cosine Similarity measures how closely two vectors align in terms of direction, but it ignores magnitude.
  • Dot Product considers both direction and magnitude, making it a better fit since we care about absolute scores.

Example:

example{width=456 height=164}

According to dot product: A>B>C Dot Product recommends Distro A as the best choice, which makes sense.

But according to cosine similarity: C>B>A

Distro C appears as the best match because it follows the same ratio (even though its scores are much lower). Since we care about absolute quality in preferred criteria rather than just proportional similarity, dot product is the better approach.

Here’s how we implemented the ranking in Python:

    def recommend(self):
        if not self.user_vector or not self.distro_vectors:
            return "No sufficient data to generate recommendations."

        scores = {}
        user_vector_np = np.array(self.user_vector)

        for distro, vector in self.distro_vectors.items():
            distro_vector_np = np.array(vector)
            score = np.dot(user_vector_np, distro_vector_np)

            scores[distro] = score

        sorted_indices = np.argsort(list(scores.values()))[::-1]
        ranked_recommendations = [(list(scores.keys())[i], list(scores.values())[i]) for i in sorted_indices]
        return ranked_recommendations

Step 4: Handling Categorical Questions

While numerical parameters like “Ease of Installation” are easy to quantify, categorical preferences (e.g., “Do you prefer a Windows-like UI?”) are more like binary or ternary preferences and are difficult to score.

To handle this, we introduced a penalty mechanism:

  • If a distribution does not match the user’s categorical preference, a penalty factor (e.g., 0.5) is applied to its score.
  • This ensures that distributions aligning with strong user preferences are ranked higher.

Here’s the modified code which ranks distros with penalties:

  def recommend(self, penalty_factor=0.5):
        if not self.user_vector or not self.distro_vectors:
            return []  # Return an empty list instead of a string

        scores = {}
        user_vector_np = np.array(self.user_vector)
        binary_params = {"updates", "UI_Look"}

        for distro, data in self.distro_vectors.items():
            distro_vector_np = np.array(data["scores"])
            final_score = np.dot(user_vector_np, distro_vector_np)

            for param in binary_params:
                if param in self.user_binary_preferences and param in data["raw_scores"]:
                    if self.user_binary_preferences[param] != data["raw_scores"][param]:
                        final_score *= penalty_factor

            scores[distro] = final_score

        return sorted(scores.items(), key=lambda x: x[1], reverse=True)

Conclusion

This ranking system forms the backbone of the chooser app, helping users find the most suitable distribution based on their needs. While our initial model looks good, we are still refining the parameters (questionnaire), expanding the dataset, and revising the app to fit the new scope

Next steps include:

  • Enhancing hardware detection to factor in compatibility scores. Given the limited time left in SoK25, I will only focus on Nvidia driver detection.
  • Improving penalty logic for better handling of categorical preferences.

This project has been an exciting challenge and I’m looking forward to refining it further. Stay tuned for more updates!

Acknowledgement

Thank you to the Season of KDE 2025 admin and mentorship team, in particular flyingcakes an Aakarsh MJ and Joseph, the KDE e.V., and the incredible KDE community for supporting this project.

Please feel free to contact me here: @drowsywings:matrix.org

Saturday, 15 March 2025

digiKam 8.6.0 Running Under Kubuntu Dear digiKam fans and users,

After four months of active maintenance and many weeks triaging bugs, the digiKam team is proud to present version 8.6.0 of its open source digital photo manager.

The digiKam team has continued to work on a better Artificial Intelligence integration in digiKam, and many parts have been improved with the 8.6.0 release.

Friday, 14 March 2025

Thursday, 13 March 2025

One of the biggest behind-the-scenes changes in the upcoming Plasma 6.4 release is the split of kwin_x11 and kwin_wayland codebases. With this blog post, I would like to delve in what led us to making such a decision and what it means for the future of kwin_x11.

Background

KWin started as an X11 window manager almost two and a half decades ago. Over the course of the years, it transformed drastically. It gained support for compositing on X, and it became a Wayland compositor.

Sharing the same codebase was critical in the early days of kwin_wayland. We already had working window management abstractions, which had been tested for many years, so we could reuse them on Wayland instead of writing new from scratch. Also, if kwin_x11 gained a new feature, then kwin_wayland would likely gain it for free too.

As time went by, kwin_wayland outgrew kwin_x11. They still shared code but they became quite distinct projects with different mental models how things operate, e.g. how pixels get on the screen or how input works. It also didn’t help that many Plasma developers jumped the X11 ship and turned to the Wayland side as part of the “eating your own dog food” practice, which eventually led to the feature freeze in KWin/X11 back in 2018 due to the lack of sufficient testing and various breakages.

Some time around 2020, we started taking a more bold and aggressive approach to Wayland session development because we saw that Plasma Wayland was trailing behind other desktop environments and something had to be changed in order to catch up. Such a policy produced great results, and Plasma is now one of the leading Wayland desktop environments. Unfortunately, it also greatly contributed to the number of regressions in the X11 session.

Another issue was that there were some features that we couldn’t make work as expected on Wayland so we had to drop them for everyone, which understandably made X11 users unhappy.

Goals

A few years ago, we started contemplating the idea of splitting the X11 and Wayland codebases because of the growing list of regressions affecting the X11 session, and architecture restrictions imposed on KWin/Wayland by the way KWin/X11 works.

That would allows us to keep KWin/X11 working as is without it breaking too often and freely change KWin/Wayland in ways that we think are best suited to make the Plasma Wayland session even better. Of course, it is not a silver bullet solution: we replace one problem with another problem (mainly related to maintenance and ensuring interface compatibility between two projects).

Details

After various discussions online and at Akademy and also seeing (impressive) Plasma Wayland usage statistics, we decided that it’s the right time to do such a split. The main kwin repository is going to host KWin/Wayland, while the kwin-x11 repository is going to host KWin/X11.

KWin/X11 and KWin/Wayland are co-installable so users can freely switch between the X11 and Wayland sessions back and forth and also make sure that updating to 6.4 is not a big hassle for distributions. You’ll be able to have only KWin/X11 or only KWin/Wayland on your computer, or both.

The codebase split doesn’t affect Xwayland support in KWin/Wayland. In other words, X11 applications will continue running on Plasma Wayland.

Extensions

Like any other Plasma component, KWin’s functionality can be extended using plugins. There’s good and bad news. The good news is that extensions written in JavaScript and QML (for example, fancy effects that are available at the KDE Store) will continue working both with kwin_x11 and kwin_wayland as expected, so extension developers don’t need to do anything about it. The bad news is that C++ extensions should be specifically targeted for kwin_x11 and kwin_wayland because neither provides API and ABI compatibility guarantees for its C++ API.

As Wayland progress moves forward, it is likely that the scripting API of KWin/Wayland will be further extended.

Future of KWin/X11

KWin/X11 will be still maintained for the foreseeable future. But that maintenance work will boil down to fixing build errors, adapting to new KDE Frameworks and Plasma APIs, and backporting window-related fixes from KWin/Wayland. There are no plans to drop KWin/X11 in the Plasma 6 lifecycle, although it’s highly possible that it will happen in Plasma 7.

KWin/X11 won’t receive new features anymore; until recently, it received new features that had been developed against KWin/Wayland passively (because both lived in the same repository). However, it might be actually a good thing because the X11 session doesn’t receive that much testing nowadays.

Tuesday, 11 March 2025

Last week I decided to clean up a bit of digital cruft. That is, I moved a few of my websites onto a single VPS, saving quite a bit of monthly server hosting costs.

What I did was that I moved VPSes from Linode (Akamai) to DigitalOcean, but also migrated a full web hotel from One to DigitalOcean (converting email accounts to email forwards).

As this is something that I do very rarely, I decided to document the process here so that I don’t have to look everything up again next time around.

The grunt work was about migrating a number of L*MP services to a LEMP server. There are a couple of tasks involved here, mainly migration of databases and getting WordPress running in a subdirectory using Nginx. The rest of the exercise had to do with the moving of nameservers and waiting for DNS propagation to get certbot to provide certificates for the new location.

Migration of MySQL databases

The migration of a database between machines can be broken down into three stages:

  1. Dumping the old database
  2. Creating a new database and user
  3. Sourcing the database contents into the new database

I choose to do it in these three stages, as I’d like to keep the old database dump as an additional backup. The other option would be to transfer the database contents in a single step, merging steps 1 and 3 into one

Nevertheless, I use mysqldump to dump the database contents, and then bzip2 to reduce the size of the dump. This is efficient since and SQL dump is quite verbose.

mysqldump -u username -p --databases databasename | grep -vE \"^(USE|CREATE DATABASE)\" | bzip2 -c - > dumpname.sql.bz2

This is derived from the answer by Anuboiz over at stack overflow. The resulting file is then transferred to the new server using scp together with the actual website.

The next step is to create a new database and a new database user. Here, I assume MariaDB (using the mysql commands), as my main target is WordPress. For other database engines, e.g. Postgresql, please check the docs for exact grammar, but the SQL commands should be very similar.

sudo mysql
mysql> CREATE DATABASE databasename;
mysql> USE databasename;
mysql> CREATE USER 'username'@'localhost' identified by 'password';
mysql> GRANT CREATE, ALTER, DROP, INSERT, UPDATE, DELETE, SELECT, REFERENCES, RELOAD on databasename.* TO 'username'@'localhost' WITH GRANT OPTION;
mysql> EXIT

Check out this digital ocean tutorial for details on the above commands.

The next step is to read the database contents into the new database. For this, we need to unzip the sql dump, e.g. bunzip2 dumpname.sql.bz2, which will result in a file called dumpname.sql. Please notice that bunzip2 unzips the file and removes the original, zipped, file. If you want to keep the original, use the -k option.

Once you have the dumpname.sql file available, you can read it into the database with the newly created user using the source command as shown below.

mysql -u username -p
enter the password here
mysql> USE databasename;
mysql> SOURCE dumpname.sql;
mysql> EXIT

Now you should have a new database with the old database contents on the new server, with an associated database user. For WordPress sites, make sure that you reflect any changes in the associated wp-config.php file.

WordPress in a subdirectory using Nginx

The other piece of the puzzle that was new to me was to run WordPress from a subdirectory, e.g. example.com/blog/, rather than from the root level, e.g. example.com/.

Removing most of the nginx server configuration, the following parts does the magic:

server {
        root /var/www/thelins.se;
        index index.php index.html;

        server_name thelins.se www.thelins.se;

...

# For root
        location / {
                try_files $uri $uri/ /index.php?$args;
        }

# For subdirectory
        location /johan/blog/ {
                try_files $uri $uri/ /johan/blog/index.php?$args;
        }

        location ~ \.php$ {
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_pass unix:/run/php/php7.4-fpm.sock;
                fastcgi_index index.php;
                include fastcgi.conf;
        }

...
}

The trick was to ensure that the subdirectory try_files statement refer to the correct index.php. Notice that this has to be done for each WordPress instance, if you happen to have multiple WordPress installations in various subdirectories on the same domain.

Conclusions

Its a bit of hassle to migrate a lot of web sites at once, but the monetary saving from moving the low traffic sites onto a single VPS, and the simplification of the management and monitoring by moving all VPSes to a single provider makes it worth it.

The last maintenance release of the 24.12 cycle is out.

For the full changelog continue reading on kdenlive.org.

Monday, 10 March 2025

Model/View Drag and Drop in Qt - Part 2

In the previous blog, you learned all about moving items within a single view, to reorder them.

In part 2, we are still talking about moving items, and still about inserting them between existing items (never overwriting items) but this time the user can move items from one view to another. A typical use case is a list of available items on the left, and a list of selected items on the right (one concrete example would be to let the user customize which buttons should appear in a toolbar). This also often includes reordering items in the right-side list, the good news being that this comes for free (no extra code needed).

Blog_Drag&Drop_Qt_part2-step1

Moving a row between treeviews, step 1

Blog_Drag&Drop_Qt_part2-step2

Moving a row between treeviews, step 2

Blog_Drag&Drop_Qt_part2-step3

Moving a row between treeviews, step 3

With Model/View separation

Example code for flat models and example code for tree models.

Setting up the view on the drag side

To allow dragging items out of the view, make sure to do the following:

☑ Call view->setDragDropMode(QAbstractItemView::DragOnly) (or DragDrop if it should support both).

☑ Call view->setDragDropOverwriteMode(false) so that QTableView calls removeRows when moving rows, rather than just clearing their cells

☑ Call view->setDefaultDropAction(Qt::MoveAction) so it's a move and not a copy

Setting up the model on the drag side

To implement dragging items out of a model, you need to implement the following:

class CountryModel : public QAbstractTableModel
{
    ~~~
    Qt::ItemFlags flags(const QModelIndex &index) const override
    {
        if (!index.isValid())
            return {}; // depending on whether you want drops as well (next section)
        return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled;
    }

    // the default is "return supportedDropActions()", let's be explicit
    Qt::DropActions supportedDragActions() const override { return Qt::MoveAction; }

    QMimeData *mimeData(const QModelIndexList &indexes) const override; // see below

    bool removeRows(int position, int rows, const QModelIndex &parent) override; // see below
};

More precisely, the check-list is the following:

☑ Reimplement flags() to add Qt::ItemIsDragEnabled in the case of a valid index

☑ Reimplement supportedDragActions() to return Qt::MoveAction

☑ Reimplement mimeData() to serialize the complete data for the dragged items. If the views are always in the same process, you can get away with serializing only node pointers (if you have that, e.g. for tree models) and application PID (to refuse dropping onto another process). Otherwise you can encode the actual data, like this:

QMimeData *CountryModel::mimeData(const QModelIndexList &indexes) const
{
    QByteArray encodedData;
    QDataStream stream(&encodedData, QIODevice::WriteOnly);
    for (const QModelIndex &index : indexes) {
        // This calls operator<<(QDataStream &stream, const CountryData &countryData), which you must implement
        stream << m_data.at(index.row());
    }

    QMimeData *mimeData = new QMimeData;
    mimeData->setData(s_mimeType, encodedData);
    return mimeData;
}

s_mimeType is the name of the type of data (make up a name, it usually starts with application/x-)

☑ Reimplement removeRows(), it will be called after a successful drop. For instance, if your data is in a vector called m_data, the implementation would look like this:

bool CountryModel::removeRows(int position, int rows, const QModelIndex &parent)
{
    beginRemoveRows(parent, position, position + rows - 1);
    for (int row = 0; row < rows; ++row)
        m_data.removeAt(position);
    endRemoveRows();
    return true;
}

Setting up the view on the drop side

☑ Call view->setDragDropMode(QAbstractItemView::DragDrop) (already done if both views should support dragging and dropping)

Setting up the model on the drop side

To implement dropping items into a model (between existing items), you need to implement the following:

class DropModel : public QAbstractTableModel
{
    ~~~
    Qt::ItemFlags flags(const QModelIndex &index) const override
    {
        if (!index.isValid())
            return Qt::ItemIsDropEnabled;
        return Qt::ItemIsEnabled | Qt::ItemIsSelectable; // and optionally Qt::ItemIsDragEnabled (previous section)
    }

    // the default is "copy only", change it
    Qt::DropActions supportedDropActions() const override { return Qt::MoveAction; }

    QStringList mimeTypes() const override { return {QString::fromLatin1(s_mimeType)}; }

    bool dropMimeData(const QMimeData *mimeData, Qt::DropAction action, 
                      int row, int column, const QModelIndex &parent) override; // see below
};

☑ Reimplement supportedDropActions() to return Qt::MoveAction

☑ Reimplement flags()
For a valid index, make sure Qt::ItemIsDropEnabled is NOT set (except for tree models where we need to drop onto items in order to insert a first child).
For the invalid index, add Qt::ItemIsDropEnabled, to allow dropping between items.

☑ Reimplement mimeTypes() and return the name of the MIME type used by the mimeData() function on the drag side.

☑ Reimplement dropMimeData()
to deserialize the data and insert new rows.
In the special case of in-process tree models, clone the dragged nodes.
In both cases, once you're done, return true, so that the drag side then deletes the dragged rows by calling removeRows() on its model.

bool DropModel::dropMimeData(const QMimeData *mimeData, Qt::DropAction action, int row, int column, const QModelIndex &parent)
{
    ~~~  // safety checks, see full example code

    if (row == -1) // drop into empty area = append
        row = rowCount(parent);

    // decode data
    const QByteArray encodedData = mimeData->data(s_mimeType);
    QDataStream stream(encodedData);
    QVector<CountryData> newCountries;
    while (!stream.atEnd()) {
        CountryData countryData;
        stream >> countryData;
        newCountries.append(countryData);
    }

    // insert new countries
    beginInsertRows(parent, row, row + newCountries.count() - 1);
    for (const CountryData &countryData : newCountries)
        m_data.insert(row++, countryData);
    endInsertRows();

    return true; // let the view handle deletion on the source side by calling removeRows there
}

Using item widgets

Example code can be found following this link.

For all kinds of widgets

On the "drag" side:

☑ Call widget->setDragDropMode(QAbstractItemView::DragOnly) or DragDrop if it should support both

☑ Call widget->setDefaultDropAction(Qt::MoveAction) so the drag starts as a move right away

On the "drop" side:

☑ Call widget->setDragDropMode(QAbstractItemView::DropOnly) or DragDrop if it should support both

☑ Reimplement supportedDropActions() to return only Qt::MoveAction

Additional requirements for QTableWidget

When using QTableWidget, in addition to the common steps above you need to:

On the "drag" side:

☑ Call item->setFlags(item->flags() & ~Qt::ItemIsDropEnabled); for each item, to disable dropping onto items.

☑ Call widget->setDragDropOverwriteMode(false) so that after a move the rows are removed rather than cleared

On the "drop" side:

☑ Call widget->setDragDropOverwriteMode(false) so that it inserts rows instead of replacing cells (the default is false for the other views anyway)

☑ Another problem is that the items created by a drop will automatically get the Qt::ItemIsDropEnabled flag, which you don't want. To solve this, use widget->setItemPrototype() with an item that has the right flags (see the example).

Additional requirements for QTreeWidget

When using QTreeWidget, you cannot disable dropping onto items (which creates a child of the item).

You could call item->setFlags(item->flags() & ~Qt::ItemIsDropEnabled); on your own items, but when QTreeWidget creates new items upon a drop, you cannot prevent them from having the flag Qt::ItemIsDropEnabled set. The prototype solution used above for QTableWidget doesn't exist for QTreeWidget.

This means, if you want to let the user build and reorganize an actual tree, you can use QTreeWidget. But if you just want a flat multi-column list, then you should use QTreeView (see previous section on model/view separation).

Addendum: Move/copy items between views

If the user should be able to choose between copying and moving items, follow the previous section and make the following changes.

With Model/View separation

On the "drag" side:

☑ Call view->setDefaultDropAction(...) to choose whether the default should be move or copy. The user can press Shift to force a move, and Ctrl to force a copy.

☑ Reimplement supportedDragActions() in the model to return Qt::MoveAction | Qt::CopyAction

On the "drop" side:

☑ Reimplement supportedDropActions() in the model to return Qt::MoveAction | Qt::CopyAction

The good news is that there's nothing else to do.

Using item widgets

On the "drag" side:

☑ Call widget->setDefaultDropAction(...) to choose whether the default should be move or copy. The user can press Shift to force a move, and Ctrl to force a copy.

Until Qt 6.10 there was no setSupportedDragActions() method in the item widget classes (that was QTBUG-87465, I implemented it for 6.10). Fortunately the default behavior is to use what supportedDropActions() returns so if you just want move and copy in both, reimplementing supportedDropActions() is enough.

On the "drop" side:

☑ Reimplement supportedDropActions() in the item widget class to return Qt::MoveAction | Qt::CopyAction

The good news is that there's nothing else to do.

Improvements to Qt

While writing and testing these code examples, I improved the following things in Qt:

  • QTBUG-1387 "Drag and drop multiple columns with item views. Dragging a row and dropping it in a column > 0 creates multiple rows.", fixed in 6.8.1
  • QTBUG-36831 "Drop indicator painted as single pixel when not shown" fixed in 6.8.1
  • QTBUG-87465 ItemWidgets: add supportedDragActions()/setSupportedDragActions(), implemented in 6.10

Conclusion

In the next blog post of this series, you will learn how to move (or copy) onto existing items, rather than between them.

The post Model/View Drag and Drop in Qt - Part 2 appeared first on KDAB.