Important: Please read the Qt Code of Conduct -

How to create custom QTabWidget

  • No, I'm not talking about subclassing. I know by default QTabWidget is a combination of QTabBar and QStackedWidget. Unfortunately QTabWidget works only with widgets. What I want to do is have a QTabBar and only one widget below, which changes its appearance, depending on some custom data class and a current tab which is selected. Therefore I have to connect each tab in my QTabBar class to a pointer of the element in the collection of my data (let's say a vector or a map), so when the tab is selected, I can get that pointer and display the element it points to to the widget below. I can use QTabWidget of course, but this means that I have to create a new widget everytime, which seems inefficient, since the widget will always be the same.
    I see that I can set data to each tab via QVariant, but I don't see the option to store a pointer in QVariant's methods. Any ideas?

    P.S. probably if I use a vector to store my data, each tab might represent an element of a vector by its index. But different elements in the vector (and tabs in QTabBar correspondingly) will be added or removed at runtime, so binding indexes of tabs to indexes of the vector won't work.

  • Unless you have really really many tabs (what would be a strange GUI then) I would just go with the QTabWidget. The overhed for having a few widgets is just not worth it implementing the whole thing yourself.

    The other option - as you already described - would be storing the data in some vector. Then each tab needs to know the index the data is stored in the vector. If it has thins information you can move the tabs around without messing it up. But still I think that seem to complicated.

  • Yes, having an int QVariant in each tab, which points to the index in the vector would work, until the user decides to close the tab, which will delete the element from the vector, and then all of the indexes of the other tabs will be messed up so I will have to re-set them again.
    I've already done the thing I want with QTabWidget, which uses dummy widgets consisting of only QScrollArea. They hold the information of each data instance and the View widget is added to the QScrollArea and refreshed according to the data the dummy widget holds, when the tab is changed. I'm just wondering if there is another way to do all this with reusable, so that my widget view can be only one and be reusable.

Log in to reply