2015-08-25 77 views
2

在我的应用程序中,我有一个QTabBar小部件,如果有许多选项卡,它使用滚动按钮。QTabBar保留标签位置

现在,在currentChanged(int)信号上,我调用了一个重命名前一个和当前选项卡的方法(调用setTabText())。

不幸的是,这重新整个QTabBar,结果如果我的当前选项卡重新绘制后,它是滚动选项卡栏中间的某个地方,它是栏上最后一个绘制选项卡,以便我看到更多前面的选项卡。有没有办法将当前标签保持在同一位置?

回答

0

我不确定如果我正确理解问题,但使用以下代码,我的应用程序运行良好。

请测试此代码以检查它是否适用于您,并查看与您的应用程序的区别。

的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)); 
    }  
}