Qt World Summit 2023: Berlin awaits! Join us now
最新版Qt 6.3已正式发布。 了解更多。
最新バージョンQt6.5がご利用いただけます。 詳細はこちら

Qt Commercial Support Weekly #20: Visualizing the Logical

In QHeaderView there is admittedly a confusing concept of referring to the different header sections, they can be referred to by their logical index or by their visual index. And then when you start trying to use the functions to go from one to the other then it can begin to get even worse. So this will hopefully go some way to clearing this up for those who need to understand how it all works together.


First of all, to set the scene, we will have five sections in the QHeaderView and to make it easy to follow they will be in alphabetical order, i.e. A to E. So our headerview starts off looking like this:


  A B C D E
Visual Index 0 1 2 3 4
Logical Index 0 1 2 3 4


The visual index is referring to where it is currently placed on the headerview, and the logical index is referring to the order that the sections were added which was in the order A to E. So the following function calls will give the following results:


Function Result Section text
logicalIndex(0) 0 A
logicalIndex(2) 2 C
logicalIndexAt(0) 0 A
visualIndex(0) 0 A
visualIndexAt(0) 0 A


So far it is fairly straightforward, so let's say we want to move A to be after C in the order by calling moveSection(0, 2), this is done using the visual index for the sections so for this case it is going to be clear what happens. Now we end up with everything looking like:


  B C A D E
Visual Index 0 1 2 3 4
Logical Index 1 2 0 3 4


and calling the same functions as before gives the following results:


Function Result Section text
logicalIndex(0) 1 B
logicalIndex(2) 0 A
logicalIndexAt(0) 1 B
visualIndex(0) 2 A
visualIndexAt(0) 1 B


And now finally lets move E to the beginning, remember this is using visual indexes so we need to call moveSection(4, 0) as it doesn't matter what order it was added in, just the order that it appears on the headerview at this point in time. Now we have the following:


  E B C A D
Visual Index 0 1 2 3 4
Logical Index 4 1 2 0 3


and calling the functions give us:


Function Result Section text
logicalIndex(0) 4 E
logicalIndex(2) 2 C
logicalIndexAt(0) 4 E
visualIndex(0) 3 A
visualIndexAt(0) 4 E


So hopefully this goes some way into clearing up how the different functions work with relation to visual indexes and logical indexes. The key thing to remember is that when you call logicalIndex() then you pass in the visual index you want the logical index for and when you call visualIndex() you pass in the logical index you want the visual index for. It is certainly easier said than done :)


Until next time, happy coding :)