QTabBar to preserve tab position

592 Views Asked by At

In my app I have a QTabBar widget that uses scroll buttons if there are many tabs.

Now, on currentChanged(int) signal I call a method that renames previous and current tab (calls setTabText()).

Unfortunately this repaints whole QTabBar and as a result if my current tab was somewhere in the middle of scrolled tab bar after repaint it is the last painted tab on the bar so that I see more preceding tabs. Is there any way to keep the current tab at the same position?

1

There are 1 best solutions below

0
On

I'm not sure if I understood the issue correctly, but with the following code, my application is working good.

Please, test this code to check if it's working for you and see the differences with your app.

main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    MainWindow mainWindow;
    mainWindow.show();
    return app.exec();
}

mainwindow.h

#ifndef _MAINWINDOW_H
#define _MAINWINDOW_H

#include <QMainWindow>
#include <QTabBar>
#include <QDebug>

class MainWindow: public QMainWindow {
    Q_OBJECT
    QTabBar *tabBar;

public:
    MainWindow();
    ~MainWindow();

private slots:
    void onCurrentChanged(int index);
};

#endif

mainwindow.cpp

#include "mainwindow.h"

MainWindow::MainWindow()
{
    tabBar = new QTabBar();

    for (int i = 1; i < 10; ++i)
    {
         tabBar->addTab(QString("###") + QString::number(i) + QString("###"));
    }

    QObject::connect(tabBar, &QTabBar::currentChanged,
                     this, &MainWindow::onCurrentChanged);

    setCentralWidget(tabBar);
}

MainWindow::~MainWindow()
{
}

void MainWindow::onCurrentChanged(int index)
{
    int currentIndex = tabBar->currentIndex();
    qDebug("currentChanged(%d), currentIndex() = %d", index, currentIndex);

    for (int i = index; i >= 0; --i)
    {
        tabBar->setTabText(i, QString::number(i+1));
    }    
}