redstrate.com/content/blog/obscure-qt4.md

1.5 KiB

title date draft tags series summary
Obscure Qt: Qt5 QMap and C++20 Ranges 2024-10-30 false
Qt
Obscure Qt
A neat trick for iterating through QMaps in Qt5, if you have access to C++20.

I was working on a project that still uses Qt5 and I wanted to port from Qt's own foreach keyword. In Qt6 it's possible to write code like this:

QMap<QString, int> map;
...
for (int value : std::as_const(map))
    cout << value << endl;

Unfortunately in Qt5 this is not possible, as it was never implemented. You don't even have asKeyValueRange()!

You may have seen it before, but someone has already written a great StackOverflow answer backporting this feature to Qt5. However, this codebase has C++20 available! (Yes, really.) The SO answer needs to add a whole bunch of extra wrapper code, but it's actually possible to use C++ for by using std::ranges::subrange:

QMap<QString, int> map;
...
for (int value : std::ranges::subrange(map.constBegin(), map.constEnd()))
    cout << value << endl;

Take care when porting to ensure the previous foreach code didn't depend on a copy of the container. Use constBegin()/constEnd() when needed to ensure the container doesn't detach.