PDA

View Full Version : QTabWidget - Catching move events



RobC
9th March 2012, 15:05
Hey all,

Would it be possible to catch the event of a tab being moved in a QTabWidget?

Lets say, in a horrible example, we have 5 tabs. I dynamically change the tab text to include "1 - ", "2 - " etc for all the tabs in their current order. If the user moves a tab, would it be possible to catch that, and rename all the tabs so the number order is still correct?

If I try this using the 'currentChanged' signal, I believe the index is being changed and thus causes a nasty crash.

Spitfire
9th March 2012, 15:17
Hmmm I think that currentChanged() is not be emitted when you move the tab, only when you click on a new one after the tab has been moved.

RobC
9th March 2012, 15:20
A very good point. I hadn't tried that when experimenting.

So, ideally a signal on the move - but there isn't one? :confused:

Spitfire
9th March 2012, 16:08
I don't think there is.

You could try subclassing the QTabWidget and reimplement void QTabWidget::tabInserted ( int index ) [virtual protected], maybe you can emit the signal from there.

RobC
9th March 2012, 17:28
No such luck. It emits a signal when the form is first set, but nothing after that point. I guess it doesn't get used when the tabs are moved. I've tried several ways, to no avail.

Time for Plan B. Well, a cup of tea and then Plan B.

norobro
9th March 2012, 19:18
So, ideally a signal on the move - but there isn't one? :confused:
See QTabBar::tabMoved(int, int). QTabWidget::tabBar() is protected so you will still need to subclass QTabWidget.

RobC
9th March 2012, 23:11
Forgive the question, but how do I reimplement QTabBar if I subclass QTabWidget?

norobro
9th March 2012, 23:29
You don't need to reimplement QTabBar. You just need to be able to call the protected function tabBar() which you can do in a subclass of QTabWidget.

Using your example:
#include <QtGui>
class TabWidget : public QTabWidget
{
Q_OBJECT
public:
TabWidget() {
setMinimumSize(300,100);
setMovable(true);
for(int i=0;i<5;++i)
addTab(new QWidget,QString("Tab %1").arg(i+1));
connect(tabBar(),SIGNAL(tabMoved(int,int)),this,SL OT(relabelTabs(int,int)));
}
public slots:
void relabelTabs(int /* from */, int /* to */){
for(int i=0;i<count();++i)
setTabText(i,QString("Tab %1").arg(i+1));
}
};

int main(int argc, char *argv[])
{
QApplication app(argc, argv);
TabWidget tw;
tw.show();
app.exec();
}
#include "main.moc"
HTH

RobC
9th March 2012, 23:35
Ah, I getcha. Sorted. Thanks for the help folks!

norobro
10th March 2012, 00:01
You're welcome.

Rather than iterating over all of the tabs, here's a better version of the slot:
void relabelTabs(int from, int to){
QString hold= tabText(from);
setTabText(from,tabText(to));
setTabText(to,hold);
}