Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qtabbar.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
5#include "private/qlayoutengine_p.h"
6#if QT_CONFIG(itemviews)
7#include "qabstractitemdelegate.h"
8#endif
9#include "qapplication.h"
10#include "qevent.h"
11#include "qpainter.h"
12#include "qstyle.h"
13#include "qstyleoption.h"
14#include "qstylepainter.h"
15#if QT_CONFIG(tabwidget)
16#include "qtabwidget.h"
17#endif
18#if QT_CONFIG(tooltip)
19#include "qtooltip.h"
20#endif
21#if QT_CONFIG(whatsthis)
22#include "qwhatsthis.h"
23#endif
24#include "private/qtextengine_p.h"
25#if QT_CONFIG(accessibility)
26#include "qaccessible.h"
27#endif
28#ifdef Q_OS_MACOS
29#include <qpa/qplatformnativeinterface.h>
30#endif
31#include "qmainwindow.h"
32#include "private/qmainwindowlayout_p.h"
33
34#include "qdebug.h"
35#include "private/qapplication_p.h"
36#include "private/qtabbar_p.h"
37
39
40using namespace Qt::StringLiterals;
41using namespace std::chrono_literals;
42
43namespace {
44class CloseButton : public QAbstractButton
45{
46 Q_OBJECT
47
48public:
49 explicit CloseButton(QWidget *parent = nullptr);
50
51 QSize sizeHint() const override;
52 QSize minimumSizeHint() const override
53 { return sizeHint(); }
54 void enterEvent(QEnterEvent *event) override;
55 void leaveEvent(QEvent *event) override;
56 void paintEvent(QPaintEvent *event) override;
57
58 void setParentClipRect(const QRect &clipRect)
59 {
60 m_parentClipRect = clipRect;
61 }
62
63protected:
64 QRect m_parentClipRect;
65};
66}
67
68QMovableTabWidget::QMovableTabWidget(QWidget *parent)
69 : QWidget(parent)
70{
71}
72
73void QMovableTabWidget::setPixmap(const QPixmap &pixmap)
74{
75 m_pixmap = pixmap;
76 update();
77}
78
79void QMovableTabWidget::paintEvent(QPaintEvent *e)
80{
81 Q_UNUSED(e);
82 QPainter p(this);
83 p.drawPixmap(0, 0, m_pixmap);
84}
85
86void QTabBarPrivate::updateMacBorderMetrics()
87{
88#if defined(Q_OS_MACOS)
89 Q_Q(QTabBar);
90
91 auto *mainWindow = qobject_cast<const QMainWindow*>(q->window());
92 if (!mainWindow)
93 return;
94
95 // Extend the unified title and toolbar area to cover the tab bar iff
96 // 1) the tab bar is in document mode
97 // 2) the tab bar is directly below an "unified" area.
98 // The extending itself is done in the Mac style,
99 // this function registers geometry and visibility state for the tab bar.
100
101 // Calculate geometry
102 int upper, lower;
103 if (documentMode) {
104 QPoint windowPos = q->mapTo(q->window(), QPoint(0,0));
105 upper = windowPos.y();
106 int tabStripHeight = q->tabSizeHint(0).height();
107 int pixelTweak = -3;
108 lower = upper + tabStripHeight + pixelTweak;
109 } else {
110 upper = 0;
111 lower = 0;
112 }
113
114 extern QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *window);
115 auto *mainWindowLayout = qt_mainwindow_layout(mainWindow);
116 mainWindowLayout->registerUnifiedToolBarArea(q, upper, lower);
117 mainWindowLayout->setUnifiedToolBarAreaEnabled(q, q->isVisible());
118#endif
119}
120
121/*!
122 \internal
123 This is basically QTabBar::initStyleOption() but
124 without the expensive QFontMetrics::elidedText() call.
125*/
126
127void QTabBarPrivate::initBasicStyleOption(QStyleOptionTab *option, int tabIndex) const
128{
129 Q_Q(const QTabBar);
130 const int totalTabs = tabList.size();
131
132 if (!option || (tabIndex < 0 || tabIndex >= totalTabs))
133 return;
134
135 const QTabBarPrivate::Tab &tab = *tabList.at(tabIndex);
136 option->initFrom(q);
137 option->state &= ~(QStyle::State_HasFocus | QStyle::State_MouseOver);
138 option->rect = q->tabRect(tabIndex);
139 const bool isCurrent = tabIndex == currentIndex;
140 option->row = 0;
141 if (tabIndex == pressedIndex)
142 option->state |= QStyle::State_Sunken;
143 if (isCurrent)
144 option->state |= QStyle::State_Selected;
145 if (isCurrent && q->hasFocus())
146 option->state |= QStyle::State_HasFocus;
147 if (!tab.enabled)
148 option->state &= ~QStyle::State_Enabled;
149 if (q->isActiveWindow())
150 option->state |= QStyle::State_Active;
151 if (!dragInProgress && option->rect == hoverRect)
152 option->state |= QStyle::State_MouseOver;
153 option->shape = shape;
154 option->text = tab.text;
155
156 if (tab.textColor.isValid())
157 option->palette.setColor(q->foregroundRole(), tab.textColor);
158 option->icon = tab.icon;
159 option->iconSize = q->iconSize(); // Will get the default value then.
160
161 option->leftButtonSize = tab.leftWidget ? tab.leftWidget->size() : QSize();
162 option->rightButtonSize = tab.rightWidget ? tab.rightWidget->size() : QSize();
163 option->documentMode = documentMode;
164
165 if (tabIndex > 0 && tabIndex - 1 == currentIndex)
166 option->selectedPosition = QStyleOptionTab::PreviousIsSelected;
167 else if (tabIndex + 1 < totalTabs && tabIndex + 1 == currentIndex)
168 option->selectedPosition = QStyleOptionTab::NextIsSelected;
169 else
170 option->selectedPosition = QStyleOptionTab::NotAdjacent;
171
172 const bool paintBeginning = (tabIndex == firstVisible) || (dragInProgress && tabIndex == pressedIndex + 1);
173 const bool paintEnd = (tabIndex == lastVisible) || (dragInProgress && tabIndex == pressedIndex - 1);
174 if (paintBeginning) {
175 if (paintEnd)
176 option->position = QStyleOptionTab::OnlyOneTab;
177 else
178 option->position = QStyleOptionTab::Beginning;
179 } else if (paintEnd) {
180 option->position = QStyleOptionTab::End;
181 } else {
182 option->position = QStyleOptionTab::Middle;
183 }
184
185#if QT_CONFIG(tabwidget)
186 if (const QTabWidget *tw = qobject_cast<const QTabWidget *>(q->parentWidget())) {
187 option->features |= QStyleOptionTab::HasFrame;
188 if (tw->cornerWidget(Qt::TopLeftCorner) || tw->cornerWidget(Qt::BottomLeftCorner))
189 option->cornerWidgets |= QStyleOptionTab::LeftCornerWidget;
190 if (tw->cornerWidget(Qt::TopRightCorner) || tw->cornerWidget(Qt::BottomRightCorner))
191 option->cornerWidgets |= QStyleOptionTab::RightCornerWidget;
192 }
193#endif
194 if (tab.measuringMinimum)
195 option->features |= QStyleOptionTab::MinimumSizeHint;
196 option->tabIndex = tabIndex;
197}
198
199/*!
200 Initialize \a option with the values from the tab at \a tabIndex. This method
201 is useful for subclasses when they need a QStyleOptionTab,
202 but don't want to fill in all the information themselves.
203
204 \sa QStyleOption::initFrom(), QTabWidget::initStyleOption()
205*/
206void QTabBar::initStyleOption(QStyleOptionTab *option, int tabIndex) const
207{
208 Q_D(const QTabBar);
209 d->initBasicStyleOption(option, tabIndex);
210
211 QRect textRect = style()->subElementRect(QStyle::SE_TabBarTabText, option, this);
212 option->text = fontMetrics().elidedText(option->text, d->elideMode, textRect.width(),
213 Qt::TextShowMnemonic);
214}
215
216/*!
217 \class QTabBar
218 \brief The QTabBar class provides a tab bar, e.g. for use in tabbed dialogs.
219
220 \ingroup basicwidgets
221 \inmodule QtWidgets
222
223 QTabBar is straightforward to use; it draws the tabs using one of
224 the predefined \l{QTabBar::Shape}{shapes}, and emits a
225 signal when a tab is selected. It can be subclassed to tailor the
226 look and feel. Qt also provides a ready-made \l{QTabWidget}.
227
228 Each tab has a tabText(), an optional tabIcon(), an optional
229 tabToolTip(), optional tabWhatsThis() and optional tabData().
230 The tabs's attributes can be changed with setTabText(), setTabIcon(),
231 setTabToolTip(), setTabWhatsThis and setTabData(). Each tabs can be
232 enabled or disabled individually with setTabEnabled().
233
234 Each tab can display text in a distinct color. The current text color
235 for a tab can be found with the tabTextColor() function. Set the text
236 color for a particular tab with setTabTextColor().
237
238 Tabs are added using addTab(), or inserted at particular positions
239 using insertTab(). The total number of tabs is given by
240 count(). Tabs can be removed from the tab bar with
241 removeTab(). Combining removeTab() and insertTab() allows you to
242 move tabs to different positions.
243
244 The \l shape property defines the tabs' appearance. The choice of
245 shape is a matter of taste, although tab dialogs (for preferences
246 and similar) invariably use \l RoundedNorth.
247 Tab controls in windows other than dialogs almost
248 always use either \l RoundedSouth or \l TriangularSouth. Many
249 spreadsheets and other tab controls in which all the pages are
250 essentially similar use \l TriangularSouth, whereas \l
251 RoundedSouth is used mostly when the pages are different (e.g. a
252 multi-page tool palette). The default in QTabBar is \l
253 RoundedNorth.
254
255 The most important part of QTabBar's API is the currentChanged()
256 signal. This is emitted whenever the current tab changes (even at
257 startup, when the current tab changes from 'none'). There is also
258 a slot, setCurrentIndex(), which can be used to select a tab
259 programmatically. The function currentIndex() returns the index of
260 the current tab, \l count holds the number of tabs.
261
262 QTabBar creates automatic mnemonic keys in the manner of QAbstractButton;
263 e.g. if a tab's label is "\&Graphics", Alt+G becomes a shortcut
264 key for switching to that tab.
265
266 The following virtual functions may need to be reimplemented in
267 order to tailor the look and feel or store extra data with each
268 tab:
269
270 \list
271 \li tabSizeHint() calcuates the size of a tab.
272 \li tabInserted() notifies that a new tab was added.
273 \li tabRemoved() notifies that a tab was removed.
274 \li tabLayoutChange() notifies that the tabs have been re-laid out.
275 \li paintEvent() paints all tabs.
276 \endlist
277
278 For subclasses, you might also need the tabRect() functions which
279 returns the visual geometry of a single tab.
280
281 \table 100%
282 \row \li \inlineimage {fusion-tabbar.png} {Tab bar with three tabs}
283 \li A tab bar shown in the \l{Qt Widget Gallery}{Fusion widget style}.
284 \row \li \inlineimage {fusion-tabbar-truncated.png} {Truncated tab bar}
285 \li A truncated tab bar shown in the Fusion widget style.
286 \endtable
287
288 \sa QTabWidget
289*/
290
291/*!
292 \enum QTabBar::Shape
293
294 This enum type lists the built-in shapes supported by QTabBar. Treat these
295 as hints as some styles may not render some of the shapes. However,
296 position should be honored.
297
298 \value RoundedNorth The normal rounded look above the pages
299
300 \value RoundedSouth The normal rounded look below the pages
301
302 \value RoundedWest The normal rounded look on the left side of the pages
303
304 \value RoundedEast The normal rounded look on the right side the pages
305
306 \value TriangularNorth Triangular tabs above the pages.
307
308 \value TriangularSouth Triangular tabs similar to those used in
309 the Excel spreadsheet, for example
310
311 \value TriangularWest Triangular tabs on the left of the pages.
312
313 \value TriangularEast Triangular tabs on the right of the pages.
314*/
315
316/*!
317 \fn void QTabBar::currentChanged(int index)
318
319 This signal is emitted when the tab bar's current tab changes. The
320 new current has the given \a index, or -1 if there isn't a new one
321 (for example, if there are no tab in the QTabBar)
322*/
323
324/*!
325 \fn void QTabBar::tabCloseRequested(int index)
326 \since 4.5
327
328 This signal is emitted when the close button on a tab is clicked.
329 The \a index is the index that should be removed.
330
331 \sa setTabsClosable()
332*/
333
334/*!
335 \fn void QTabBar::tabMoved(int from, int to)
336 \since 4.5
337
338 This signal is emitted when the tab has moved the tab
339 at index position \a from to index position \a to.
340
341 note: QTabWidget will automatically move the page when
342 this signal is emitted from its tab bar.
343
344 \sa moveTab()
345*/
346
347/*!
348 \fn void QTabBar::tabBarClicked(int index)
349
350 This signal is emitted when user clicks on a tab at an \a index.
351
352 \a index is the index of a clicked tab, or -1 if no tab is under the cursor.
353
354 \since 5.2
355*/
356
357/*!
358 \fn void QTabBar::tabBarDoubleClicked(int index)
359
360 This signal is emitted when the user double clicks on a tab at \a index.
361
362 \a index refers to the tab clicked, or -1 if no tab is under the cursor.
363
364 \since 5.2
365*/
366
367void QTabBarPrivate::init()
368{
369 Q_Q(QTabBar);
370 leftB = new QToolButton(q);
371 leftB->setObjectName(u"ScrollLeftButton"_s);
372 leftB->setAutoRepeat(true);
373 QObjectPrivate::connect(leftB, &QToolButton::clicked,
374 this, &QTabBarPrivate::scrollTabs);
375 leftB->hide();
376 rightB = new QToolButton(q);
377 rightB->setObjectName(u"ScrollRightButton"_s);
378 rightB->setAutoRepeat(true);
379 QObjectPrivate::connect(rightB, &QToolButton::clicked,
380 this, &QTabBarPrivate::scrollTabs);
381 rightB->hide();
382 q->setFocusPolicy(Qt::TabFocus);
383
384#if QT_CONFIG(accessibility)
385 leftB->setAccessibleName(QTabBar::tr("Scroll Left"));
386 rightB->setAccessibleName(QTabBar::tr("Scroll Right"));
387#endif
388 q->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);
389 elideMode = Qt::TextElideMode(q->style()->styleHint(QStyle::SH_TabBar_ElideMode, nullptr, q));
390 useScrollButtons = !q->style()->styleHint(QStyle::SH_TabBar_PreferNoArrows, nullptr, q);
391}
392
393int QTabBarPrivate::indexAtPos(const QPoint &p) const
394{
395 Q_Q(const QTabBar);
396 if (q->tabRect(currentIndex).contains(p))
397 return currentIndex;
398 for (int i = 0; i < tabList.size(); ++i)
399 if (tabList.at(i)->enabled && q->tabRect(i).contains(p))
400 return i;
401 return -1;
402}
403
404void QTabBarPrivate::layoutTabs()
405{
406 Q_Q(QTabBar);
407 layoutDirty = false;
408 QSize size = q->size();
409 int last, available;
410 int maxExtent;
411 bool vertTabs = verticalTabs(shape);
412 int tabChainIndex = 0;
413 int hiddenTabs = 0;
414 const auto *style = q->style();
415
416 Qt::Alignment tabAlignment = Qt::Alignment(style->styleHint(QStyle::SH_TabBar_Alignment, nullptr, q));
417 QList<QLayoutStruct> tabChain(tabList.size() + 2);
418
419 // We put an empty item at the front and back and set its expansive attribute
420 // depending on tabAlignment and expanding.
421 tabChain[tabChainIndex].init();
422 tabChain[tabChainIndex].expansive = (!expanding)
423 && (tabAlignment != Qt::AlignLeft)
424 && (tabAlignment != Qt::AlignJustify);
425 tabChain[tabChainIndex].empty = true;
426 ++tabChainIndex;
427
428 // We now go through our list of tabs and set the minimum size and the size hint
429 // This will allow us to elide text if necessary. Since we don't set
430 // a maximum size, tabs will EXPAND to fill up the empty space.
431 // Since tab widget is rather *ahem* strict about keeping the geometry of the
432 // tab bar to its absolute minimum, this won't bleed through, but will show up
433 // if you use tab bar on its own (a.k.a. not a bug, but a feature).
434 // Update: if expanding is false, we DO set a maximum size to prevent the tabs
435 // being wider than necessary.
436 if (!vertTabs) {
437 int minx = 0;
438 int x = 0;
439 int maxHeight = 0;
440 for (int i = 0; i < tabList.size(); ++i) {
441 const auto tab = tabList.at(i);
442 if (!tab->visible) {
443 ++hiddenTabs;
444 continue;
445 }
446 QSize sz = q->tabSizeHint(i);
447 tab->maxRect = QRect(x, 0, sz.width(), sz.height());
448 x += sz.width();
449 maxHeight = qMax(maxHeight, sz.height());
450 sz = q->minimumTabSizeHint(i);
451 tab->minRect = QRect(minx, 0, sz.width(), sz.height());
452 minx += sz.width();
453 tabChain[tabChainIndex].init();
454 tabChain[tabChainIndex].sizeHint = tab->maxRect.width();
455 tabChain[tabChainIndex].minimumSize = sz.width();
456 tabChain[tabChainIndex].empty = false;
457 tabChain[tabChainIndex].expansive = true;
458
459 if (!expanding)
460 tabChain[tabChainIndex].maximumSize = tabChain[tabChainIndex].sizeHint;
461 ++tabChainIndex;
462 }
463
464 last = minx;
465 available = size.width();
466 maxExtent = maxHeight;
467 } else {
468 int miny = 0;
469 int y = 0;
470 int maxWidth = 0;
471 for (int i = 0; i < tabList.size(); ++i) {
472 auto tab = tabList.at(i);
473 if (!tab->visible) {
474 ++hiddenTabs;
475 continue;
476 }
477 QSize sz = q->tabSizeHint(i);
478 tab->maxRect = QRect(0, y, sz.width(), sz.height());
479 y += sz.height();
480 maxWidth = qMax(maxWidth, sz.width());
481 sz = q->minimumTabSizeHint(i);
482 tab->minRect = QRect(0, miny, sz.width(), sz.height());
483 miny += sz.height();
484 tabChain[tabChainIndex].init();
485 tabChain[tabChainIndex].sizeHint = tab->maxRect.height();
486 tabChain[tabChainIndex].minimumSize = sz.height();
487 tabChain[tabChainIndex].empty = false;
488 tabChain[tabChainIndex].expansive = true;
489
490 if (!expanding)
491 tabChain[tabChainIndex].maximumSize = tabChain[tabChainIndex].sizeHint;
492 ++tabChainIndex;
493 }
494
495 last = miny;
496 available = size.height();
497 maxExtent = maxWidth;
498 }
499
500 // Mirror our front item.
501 tabChain[tabChainIndex].init();
502 tabChain[tabChainIndex].expansive = (!expanding)
503 && (tabAlignment != Qt::AlignRight)
504 && (tabAlignment != Qt::AlignJustify);
505 tabChain[tabChainIndex].empty = true;
506 Q_ASSERT(tabChainIndex == tabChain.size() - 1 - hiddenTabs); // add an assert just to make sure.
507
508 // Do the calculation
509 qGeomCalc(tabChain, 0, tabChain.size(), 0, qMax(available, last), 0);
510
511 // Use the results
512 hiddenTabs = 0;
513 for (int i = 0; i < tabList.size(); ++i) {
514 auto tab = tabList.at(i);
515 if (!tab->visible) {
516 tab->rect = QRect();
517 ++hiddenTabs;
518 continue;
519 }
520 const QLayoutStruct &lstruct = tabChain.at(i + 1 - hiddenTabs);
521 if (!vertTabs)
522 tab->rect.setRect(lstruct.pos, 0, lstruct.size, maxExtent);
523 else
524 tab->rect.setRect(0, lstruct.pos, maxExtent, lstruct.size);
525 }
526
527 if (useScrollButtons && tabList.size() && last > available) {
528 const QRect scrollRect = normalizedScrollRect(0);
529
530 Q_Q(QTabBar);
531 QStyleOption opt;
532 opt.initFrom(q);
533 QRect scrollButtonLeftRect = style->subElementRect(QStyle::SE_TabBarScrollLeftButton, &opt, q);
534 QRect scrollButtonRightRect = style->subElementRect(QStyle::SE_TabBarScrollRightButton, &opt, q);
535 int scrollButtonWidth = style->pixelMetric(QStyle::PM_TabBarScrollButtonWidth, &opt, q);
536
537 const auto setIconOr = [](QToolButton *tb, const QIcon &icon, Qt::ArrowType arrowType) {
538 if (icon.isNull())
539 tb->setArrowType(arrowType);
540 else
541 tb->setIcon(icon);
542 };
543 // Normally SE_TabBarScrollLeftButton should have the same width as PM_TabBarScrollButtonWidth.
544 // But if that is not the case, we set the actual button width to PM_TabBarScrollButtonWidth, and
545 // use the extra space from SE_TabBarScrollLeftButton as margins towards the tabs.
546 if (vertTabs) {
547 scrollButtonLeftRect.setHeight(scrollButtonWidth);
548 scrollButtonRightRect.setY(scrollButtonRightRect.bottom() + 1 - scrollButtonWidth);
549 scrollButtonRightRect.setHeight(scrollButtonWidth);
550 const auto upIcon = style->standardIcon(QStyle::SP_TabScrollUpButton, &opt, q);
551 const auto downIcon = style->standardIcon(QStyle::SP_TabScrollDownButton, &opt, q);
552 setIconOr(leftB, upIcon, Qt::UpArrow);
553 setIconOr(rightB, downIcon, Qt::DownArrow);
554 } else if (q->layoutDirection() == Qt::RightToLeft) {
555 scrollButtonRightRect.setWidth(scrollButtonWidth);
556 scrollButtonLeftRect.setX(scrollButtonLeftRect.right() + 1 - scrollButtonWidth);
557 scrollButtonLeftRect.setWidth(scrollButtonWidth);
558 const auto leftIcon = style->standardIcon(QStyle::SP_TabScrollLeftButton, &opt, q);
559 const auto rightIcon = style->standardIcon(QStyle::SP_TabScrollRightButton, &opt, q);
560 setIconOr(leftB, rightIcon, Qt::RightArrow);
561 setIconOr(rightB, leftIcon, Qt::LeftArrow);
562 } else {
563 scrollButtonLeftRect.setWidth(scrollButtonWidth);
564 scrollButtonRightRect.setX(scrollButtonRightRect.right() + 1 - scrollButtonWidth);
565 scrollButtonRightRect.setWidth(scrollButtonWidth);
566 const auto leftIcon = style->standardIcon(QStyle::SP_TabScrollLeftButton, &opt, q);
567 const auto rightIcon = style->standardIcon(QStyle::SP_TabScrollRightButton, &opt, q);
568 setIconOr(leftB, leftIcon, Qt::LeftArrow);
569 setIconOr(rightB, rightIcon, Qt::RightArrow);
570 }
571
572 leftB->setGeometry(scrollButtonLeftRect);
573 leftB->setEnabled(false);
574 leftB->show();
575
576 rightB->setGeometry(scrollButtonRightRect);
577 rightB->setEnabled(last + scrollRect.left() > scrollRect.x() + scrollRect.width());
578 rightB->show();
579 } else {
580 rightB->hide();
581 leftB->hide();
582 }
583
584 layoutWidgets();
585 q->tabLayoutChange();
586}
587
588QRect QTabBarPrivate::scrollRect(int index) const
589{
590 const QRect r = normalizedScrollRect(index);
591 return verticalTabs(shape) ? QRect(QPoint(r.y(), r.x()), r.size().transposed()) : r;
592}
593
594QRect QTabBarPrivate::normalizedScrollRect(int index) const
595{
596 // "Normalized scroll rect" means return the free space on the tab bar
597 // that doesn't overlap with scroll buttons or tear indicators, and
598 // always return the rect as horizontal Qt::LeftToRight, even if the
599 // tab bar itself is in a different orientation.
600
601 Q_Q(const QTabBar);
602 // If scrollbuttons are not visible, then there's no tear either, and
603 // the entire widget is the scroll rect.
604 if (leftB->isHidden())
605 return verticalTabs(shape) ? q->rect().transposed() : q->rect();
606
607 QStyleOptionTab opt;
608 q->initStyleOption(&opt, currentIndex);
609 opt.rect = q->rect();
610
611 const auto style = q->style();
612 QRect scrollButtonLeftRect = style->subElementRect(QStyle::SE_TabBarScrollLeftButton, &opt, q);
613 QRect scrollButtonRightRect = style->subElementRect(QStyle::SE_TabBarScrollRightButton, &opt, q);
614 QRect tearLeftRect = style->subElementRect(QStyle::SE_TabBarTearIndicatorLeft, &opt, q);
615 QRect tearRightRect = style->subElementRect(QStyle::SE_TabBarTearIndicatorRight, &opt, q);
616
617 if (verticalTabs(shape)) {
618 int topEdge, bottomEdge;
619 bool leftButtonIsOnTop = scrollButtonLeftRect.y() < q->height() / 2;
620 bool rightButtonIsOnTop = scrollButtonRightRect.y() < q->height() / 2;
621
622 if (leftButtonIsOnTop && rightButtonIsOnTop) {
623 topEdge = scrollButtonRightRect.bottom() + 1;
624 bottomEdge = q->height();
625 } else if (!leftButtonIsOnTop && !rightButtonIsOnTop) {
626 topEdge = 0;
627 bottomEdge = scrollButtonLeftRect.top();
628 } else {
629 topEdge = scrollButtonLeftRect.bottom() + 1;
630 bottomEdge = scrollButtonRightRect.top();
631 }
632
633 const auto lastTab = lastVisibleTab();
634 if (!lastTab)
635 return {};
636 bool tearTopVisible = index != 0 && topEdge != -scrollOffset;
637 bool tearBottomVisible = index != tabList.size() - 1 && bottomEdge != lastTab->rect.bottom() + 1 - scrollOffset;
638 if (tearTopVisible && !tearLeftRect.isNull())
639 topEdge = tearLeftRect.bottom() + 1;
640 if (tearBottomVisible && !tearRightRect.isNull())
641 bottomEdge = tearRightRect.top();
642
643 return QRect(topEdge, 0, bottomEdge - topEdge, q->height());
644 } else {
645 if (q->layoutDirection() == Qt::RightToLeft) {
646 scrollButtonLeftRect = QStyle::visualRect(Qt::RightToLeft, q->rect(), scrollButtonLeftRect);
647 scrollButtonRightRect = QStyle::visualRect(Qt::RightToLeft, q->rect(), scrollButtonRightRect);
648 tearLeftRect = QStyle::visualRect(Qt::RightToLeft, q->rect(), tearLeftRect);
649 tearRightRect = QStyle::visualRect(Qt::RightToLeft, q->rect(), tearRightRect);
650 }
651
652 int leftEdge, rightEdge;
653 bool leftButtonIsOnLeftSide = scrollButtonLeftRect.x() < q->width() / 2;
654 bool rightButtonIsOnLeftSide = scrollButtonRightRect.x() < q->width() / 2;
655
656 if (leftButtonIsOnLeftSide && rightButtonIsOnLeftSide) {
657 leftEdge = scrollButtonRightRect.right() + 1;
658 rightEdge = q->width();
659 } else if (!leftButtonIsOnLeftSide && !rightButtonIsOnLeftSide) {
660 leftEdge = 0;
661 rightEdge = scrollButtonLeftRect.left();
662 } else {
663 leftEdge = scrollButtonLeftRect.right() + 1;
664 rightEdge = scrollButtonRightRect.left();
665 }
666
667 const auto lastTab = lastVisibleTab();
668 if (!lastTab)
669 return {};
670 bool tearLeftVisible = index != 0 && leftEdge != -scrollOffset;
671 bool tearRightVisible = index != tabList.size() - 1 && rightEdge != lastTab->rect.right() + 1 - scrollOffset;
672 if (tearLeftVisible && !tearLeftRect.isNull())
673 leftEdge = tearLeftRect.right() + 1;
674 if (tearRightVisible && !tearRightRect.isNull())
675 rightEdge = tearRightRect.left();
676
677 return QRect(leftEdge, 0, rightEdge - leftEdge, q->height());
678 }
679}
680
681int QTabBarPrivate::hoveredTabIndex() const
682{
683 if (dragInProgress)
684 return currentIndex;
685 if (hoverIndex >= 0)
686 return hoverIndex;
687 return -1;
688}
689
690void QTabBarPrivate::makeVisible(int index)
691{
692 Q_Q(QTabBar);
693 if (!validIndex(index))
694 return;
695
696 const auto lastTab = lastVisibleTab();
697 const QRect tabRect = tabList.at(index)->rect;
698 const int oldScrollOffset = scrollOffset;
699 const bool horiz = !verticalTabs(shape);
700 const int available = horiz ? q->width() : q->height();
701 const int tabStart = horiz ? tabRect.left() : tabRect.top();
702 const int tabEnd = horiz ? tabRect.right() : tabRect.bottom();
703 const int lastTabEnd = lastTab ? (horiz ? lastTab->rect.right() : lastTab->rect.bottom()) : 0;
704 const QRect scrollRect = normalizedScrollRect(index);
705 const QRect entireScrollRect = normalizedScrollRect(0); // ignore tears
706 const int scrolledTabBarStart = qMax(1, scrollRect.left() + scrollOffset);
707 const int scrolledTabBarEnd = qMin(lastTabEnd - 1, scrollRect.right() + scrollOffset);
708
709 if (available >= lastTabEnd) {
710 // the entire tabbar fits, reset scroll
711 scrollOffset = 0;
712 } else if (tabStart < scrolledTabBarStart) {
713 // Tab is outside on the left, so scroll left.
714 scrollOffset = tabStart - scrollRect.left();
715 } else if (tabEnd > scrolledTabBarEnd) {
716 // Tab is outside on the right, so scroll right.
717 scrollOffset = qMax(0, tabEnd - scrollRect.right());
718 } else if (scrollOffset + entireScrollRect.width() > lastTabEnd + 1) {
719 // fill any free space on the right without overshooting
720 scrollOffset = qMax(0, lastTabEnd - entireScrollRect.width() + 1);
721 }
722
723 leftB->setEnabled(scrollOffset > -scrollRect.left());
724 rightB->setEnabled(scrollOffset < lastTabEnd - scrollRect.right());
725
726 if (oldScrollOffset != scrollOffset) {
727 q->update();
728 layoutWidgets();
729 }
730}
731
732void QTabBarPrivate::killSwitchTabTimer()
733{
734 switchTabTimer.stop();
735 switchTabCurrentIndex = -1;
736}
737
738void QTabBarPrivate::layoutTab(int index)
739{
740 Q_Q(QTabBar);
741 Q_ASSERT(index >= 0);
742
743 const Tab *tab = tabList.at(index);
744 bool vertical = verticalTabs(shape);
745 if (!(tab->leftWidget || tab->rightWidget))
746 return;
747
748 QStyleOptionTab opt;
749 q->initStyleOption(&opt, index);
750 if (tab->leftWidget) {
751 QRect rect = q->style()->subElementRect(QStyle::SE_TabBarTabLeftButton, &opt, q);
752 QPoint p = rect.topLeft();
753 if (tab->dragOffset != 0) {
754 if (vertical)
755 p.setY(p.y() + tab->dragOffset);
756 else
757 p.setX(p.x() + tab->dragOffset);
758 }
759 tab->leftWidget->move(p);
760 }
761 if (tab->rightWidget) {
762 QRect rect = q->style()->subElementRect(QStyle::SE_TabBarTabRightButton, &opt, q);
763 QPoint p = rect.topLeft();
764 if (tab->dragOffset != 0) {
765 if (vertical)
766 p.setY(p.y() + tab->dragOffset);
767 else
768 p.setX(p.x() + tab->dragOffset);
769 }
770 tab->rightWidget->move(p);
771 }
772}
773
774void QTabBarPrivate::layoutWidgets(int start)
775{
776 Q_Q(QTabBar);
777 for (int i = start; i < q->count(); ++i) {
778 layoutTab(i);
779 }
780}
781
782void QTabBarPrivate::autoHideTabs()
783{
784 Q_Q(QTabBar);
785
786 if (autoHide)
787 q->setVisible(q->count() > 1);
788}
789
790void QTabBarPrivate::closeTab()
791{
792 Q_Q(QTabBar);
793 QObject *object = q->sender();
794 int tabToClose = -1;
795 QTabBar::ButtonPosition closeSide = (QTabBar::ButtonPosition)q->style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, nullptr, q);
796 for (int i = 0; i < tabList.size(); ++i) {
797 if (closeSide == QTabBar::LeftSide) {
798 if (tabList.at(i)->leftWidget == object) {
799 tabToClose = i;
800 break;
801 }
802 } else {
803 if (tabList.at(i)->rightWidget == object) {
804 tabToClose = i;
805 break;
806 }
807 }
808 }
809 if (tabToClose != -1)
810 emit q->tabCloseRequested(tabToClose);
811}
812
813void QTabBarPrivate::scrollTabs()
814{
815 Q_Q(QTabBar);
816 const QObject *sender = q->sender();
817 const bool horizontal = !verticalTabs(shape);
818 const QRect scrollRect = normalizedScrollRect().translated(scrollOffset, 0);
819
820 if (sender == leftB) {
821 for (qsizetype i = tabList.size() - 1; i >= 0; --i) {
822 const auto *tab = tabList.at(i);
823 if (!tab->visible)
824 continue;
825 int start = horizontal ? tab->rect.left() : tab->rect.top();
826 if (start < scrollRect.left()) {
827 makeVisible(i);
828 return;
829 }
830 }
831 } else if (sender == rightB) {
832 for (qsizetype i = 0; i < tabList.size(); ++i) {
833 const auto *tab = tabList.at(i);
834 if (!tab->visible)
835 continue;
836 const auto &tabRect = tab->rect;
837 int start = horizontal ? tabRect.left() : tabRect.top();
838 int end = horizontal ? tabRect.right() : tabRect.bottom();
839 if (end > scrollRect.right() && start > scrollRect.left()) {
840 makeVisible(i);
841 return;
842 }
843 }
844 }
845}
846
847void QTabBarPrivate::refresh()
848{
849 Q_Q(QTabBar);
850
851 // be safe in case a subclass is also handling move with the tabs
852 if (pressedIndex != -1
853 && movable
854 && mouseButtons == Qt::NoButton) {
855 moveTabFinished(pressedIndex);
856 if (!validIndex(pressedIndex))
857 pressedIndex = -1;
858 }
859
860 if (!q->isVisible()) {
861 layoutDirty = true;
862 } else {
863 layoutTabs();
864 makeVisible(currentIndex);
865 q->update();
866 q->updateGeometry();
867 }
868}
869
870/*!
871 Creates a new tab bar with the given \a parent.
872*/
873QTabBar::QTabBar(QWidget* parent)
874 :QWidget(*new QTabBarPrivate, parent, { })
875{
876 Q_D(QTabBar);
877 d->init();
878}
879
880
881/*!
882 Destroys the tab bar.
883*/
884QTabBar::~QTabBar()
885{
886}
887
888/*!
889 \property QTabBar::shape
890 \brief the shape of the tabs in the tab bar
891
892 Possible values for this property are described by the Shape enum.
893*/
894
895
896QTabBar::Shape QTabBar::shape() const
897{
898 Q_D(const QTabBar);
899 return d->shape;
900}
901
902void QTabBar::setShape(Shape shape)
903{
904 Q_D(QTabBar);
905 if (d->shape == shape)
906 return;
907 d->shape = shape;
908 d->refresh();
909}
910
911/*!
912 \property QTabBar::drawBase
913 \brief defines whether or not tab bar should draw its base.
914
915 If true then QTabBar draws a base in relation to the styles overlap.
916 Otherwise only the tabs are drawn.
917
918 \sa QStyle::pixelMetric(), QStyle::PM_TabBarBaseOverlap, QStyleOptionTabBarBase
919*/
920
921void QTabBar::setDrawBase(bool drawBase)
922{
923 Q_D(QTabBar);
924 if (d->drawBase == drawBase)
925 return;
926 d->drawBase = drawBase;
927 update();
928}
929
930bool QTabBar::drawBase() const
931{
932 Q_D(const QTabBar);
933 return d->drawBase;
934}
935
936/*!
937 Adds a new tab with text \a text. Returns the new
938 tab's index.
939*/
940int QTabBar::addTab(const QString &text)
941{
942 return insertTab(-1, text);
943}
944
945/*!
946 \overload
947
948 Adds a new tab with icon \a icon and text \a
949 text. Returns the new tab's index.
950*/
951int QTabBar::addTab(const QIcon& icon, const QString &text)
952{
953 return insertTab(-1, icon, text);
954}
955
956/*!
957 Inserts a new tab with text \a text at position \a index. If \a
958 index is out of range, the new tab is appended. Returns the new
959 tab's index.
960*/
961int QTabBar::insertTab(int index, const QString &text)
962{
963 return insertTab(index, QIcon(), text);
964}
965
966/*!\overload
967
968 Inserts a new tab with icon \a icon and text \a text at position
969 \a index. If \a index is out of range, the new tab is
970 appended. Returns the new tab's index.
971
972 If the QTabBar was empty before this function is called, the inserted tab
973 becomes the current tab.
974
975 Inserting a new tab at an index less than or equal to the current index
976 will increment the current index, but keep the current tab.
977*/
978int QTabBar::insertTab(int index, const QIcon& icon, const QString &text)
979{
980 Q_D(QTabBar);
981 if (!d->validIndex(index)) {
982 index = d->tabList.size();
983 d->tabList.append(new QTabBarPrivate::Tab(icon, text));
984 } else {
985 d->tabList.insert(index, new QTabBarPrivate::Tab(icon, text));
986 }
987#ifndef QT_NO_SHORTCUT
988 d->tabList.at(index)->shortcutId = grabShortcut(QKeySequence::mnemonic(text));
989#endif
990 d->firstVisible = qMax(qMin(index, d->firstVisible), 0);
991 d->refresh();
992 if (d->tabList.size() == 1)
993 setCurrentIndex(index);
994 else if (index <= d->currentIndex)
995 ++d->currentIndex;
996
997 if (index <= d->lastVisible)
998 ++d->lastVisible;
999 else
1000 d->lastVisible = index;
1001
1002 if (d->closeButtonOnTabs) {
1003 QStyleOptionTab opt;
1004 initStyleOption(&opt, index);
1005 ButtonPosition closeSide = (ButtonPosition)style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, nullptr, this);
1006 QAbstractButton *closeButton = new CloseButton(this);
1007 QObjectPrivate::connect(closeButton, &CloseButton::clicked,
1008 d, &QTabBarPrivate::closeTab);
1009 setTabButton(index, closeSide, closeButton);
1010 }
1011
1012 for (const auto tab : std::as_const(d->tabList)) {
1013 if (tab->lastTab >= index)
1014 ++tab->lastTab;
1015 }
1016
1017 if (isVisible() && tabAt(d->mousePosition) == index) {
1018 if (d->scrollRect(index).contains(d->mousePosition)) {
1019 d->hoverIndex = index;
1020 d->hoverRect = tabRect(index);
1021 } else {
1022 d->hoverIndex = -1;
1023 d->hoverRect = QRect();
1024 }
1025 }
1026
1027 tabInserted(index);
1028 d->autoHideTabs();
1029 return index;
1030}
1031
1032
1033/*!
1034 Removes the tab at position \a index.
1035
1036 \sa SelectionBehavior
1037 */
1038void QTabBar::removeTab(int index)
1039{
1040 Q_D(QTabBar);
1041 if (d->validIndex(index)) {
1042 auto removedTab = d->tabList.at(index);
1043 if (d->dragInProgress)
1044 d->moveTabFinished(d->pressedIndex);
1045
1046#ifndef QT_NO_SHORTCUT
1047 releaseShortcut(d->tabList.at(index)->shortcutId);
1048#endif
1049 if (removedTab->leftWidget) {
1050 removedTab->leftWidget->hide();
1051 removedTab->leftWidget->deleteLater();
1052 removedTab->leftWidget = nullptr;
1053 }
1054 if (removedTab->rightWidget) {
1055 removedTab->rightWidget->hide();
1056 removedTab->rightWidget->deleteLater();
1057 removedTab->rightWidget = nullptr;
1058 }
1059
1060 int newIndex = removedTab->lastTab;
1061 d->tabList.removeAt(index);
1062 delete removedTab;
1063 for (auto tab : std::as_const(d->tabList)) {
1064 if (tab->lastTab == index)
1065 tab->lastTab = -1;
1066 if (tab->lastTab > index)
1067 --tab->lastTab;
1068 }
1069
1070 d->calculateFirstLastVisible(index, false, true);
1071
1072 if (index == d->currentIndex) {
1073 // The current tab is going away, in order to make sure
1074 // we emit that "current has changed", we need to reset this
1075 // around.
1076 d->currentIndex = -1;
1077 if (d->tabList.size() > 0) {
1078 switch(d->selectionBehaviorOnRemove) {
1079 case SelectPreviousTab:
1080 if (newIndex > index)
1081 newIndex--;
1082 if (d->validIndex(newIndex) && d->tabList.at(newIndex)->visible)
1083 break;
1084 Q_FALLTHROUGH();
1085 case SelectRightTab:
1086 newIndex = qBound(d->firstVisible, index, d->lastVisible);
1087 break;
1088 case SelectLeftTab:
1089 newIndex = qBound(d->firstVisible, index-1, d->lastVisible);
1090 break;
1091 default:
1092 break;
1093 }
1094
1095 if (d->validIndex(newIndex)) {
1096 // don't loose newIndex's old through setCurrentIndex
1097 int bump = d->tabList.at(newIndex)->lastTab;
1098 setCurrentIndex(newIndex);
1099 d->tabList.at(newIndex)->lastTab = bump;
1100 } else {
1101 // we had a valid current index, but there are no visible tabs left
1102 emit currentChanged(-1);
1103 }
1104 } else {
1105 emit currentChanged(-1);
1106 }
1107 } else if (index < d->currentIndex) {
1108 setCurrentIndex(d->currentIndex - 1);
1109 }
1110 d->refresh();
1111 d->autoHideTabs();
1112 if (d->hoverRect.isValid()) {
1113 update(d->hoverRect);
1114 d->hoverIndex = tabAt(d->mousePosition);
1115 if (d->validIndex(d->hoverIndex)
1116 && d->scrollRect(d->hoverIndex).contains(d->mousePosition)) {
1117 d->hoverRect = tabRect(d->hoverIndex);
1118 update(d->hoverRect);
1119 } else {
1120 d->hoverRect = QRect();
1121 d->hoverIndex = -1;
1122 }
1123 }
1124 tabRemoved(index);
1125 }
1126}
1127
1128
1129/*!
1130 Returns \c true if the tab at position \a index is enabled; otherwise
1131 returns \c false.
1132*/
1133bool QTabBar::isTabEnabled(int index) const
1134{
1135 Q_D(const QTabBar);
1136 if (const QTabBarPrivate::Tab *tab = d->at(index))
1137 return tab->enabled;
1138 return false;
1139}
1140
1141/*!
1142 If \a enabled is true then the tab at position \a index is
1143 enabled; otherwise the item at position \a index is disabled.
1144*/
1145void QTabBar::setTabEnabled(int index, bool enabled)
1146{
1147 Q_D(QTabBar);
1148 if (QTabBarPrivate::Tab *tab = d->at(index)) {
1149 tab->enabled = enabled;
1150#ifndef QT_NO_SHORTCUT
1151 setShortcutEnabled(tab->shortcutId, enabled);
1152#endif
1153 update();
1154 if (!enabled && index == d->currentIndex)
1155 setCurrentIndex(d->selectNewCurrentIndexFrom(index+1));
1156 else if (enabled && !isTabVisible(d->currentIndex))
1157 setCurrentIndex(d->selectNewCurrentIndexFrom(index));
1158 }
1159}
1160
1161
1162/*!
1163 Returns true if the tab at position \a index is visible; otherwise
1164 returns false.
1165 \since 5.15
1166*/
1167bool QTabBar::isTabVisible(int index) const
1168{
1169 Q_D(const QTabBar);
1170 if (d->validIndex(index))
1171 return d->tabList.at(index)->visible;
1172 return false;
1173}
1174
1175/*!
1176 If \a visible is true, make the tab at position \a index visible,
1177 otherwise make it hidden.
1178 \since 5.15
1179*/
1180void QTabBar::setTabVisible(int index, bool visible)
1181{
1182 Q_D(QTabBar);
1183 if (QTabBarPrivate::Tab *tab = d->at(index)) {
1184 d->layoutDirty = (visible != tab->visible);
1185 if (!d->layoutDirty)
1186 return;
1187 tab->visible = visible;
1188 if (tab->leftWidget)
1189 tab->leftWidget->setVisible(visible);
1190 if (tab->rightWidget)
1191 tab->rightWidget->setVisible(visible);
1192#ifndef QT_NO_SHORTCUT
1193 setShortcutEnabled(tab->shortcutId, visible);
1194#endif
1195 d->calculateFirstLastVisible(index, visible, false);
1196 if (!visible && index == d->currentIndex) {
1197 const int newindex = d->selectNewCurrentIndexFrom(index+1);
1198 setCurrentIndex(newindex);
1199 }
1200 update();
1201 }
1202}
1203
1204
1205/*!
1206 Returns the text of the tab at position \a index, or an empty
1207 string if \a index is out of range.
1208*/
1209QString QTabBar::tabText(int index) const
1210{
1211 Q_D(const QTabBar);
1212 if (const QTabBarPrivate::Tab *tab = d->at(index))
1213 return tab->text;
1214 return QString();
1215}
1216
1217/*!
1218 Sets the text of the tab at position \a index to \a text.
1219*/
1220void QTabBar::setTabText(int index, const QString &text)
1221{
1222 Q_D(QTabBar);
1223 if (QTabBarPrivate::Tab *tab = d->at(index)) {
1224 d->textSizes.remove(tab->text);
1225 tab->text = text;
1226#ifndef QT_NO_SHORTCUT
1227 releaseShortcut(tab->shortcutId);
1228 tab->shortcutId = grabShortcut(QKeySequence::mnemonic(text));
1229 setShortcutEnabled(tab->shortcutId, tab->enabled);
1230#endif
1231 d->refresh();
1232 }
1233}
1234
1235/*!
1236 Returns the text color of the tab with the given \a index, or a invalid
1237 color if \a index is out of range.
1238
1239 \sa setTabTextColor()
1240*/
1241QColor QTabBar::tabTextColor(int index) const
1242{
1243 Q_D(const QTabBar);
1244 if (const QTabBarPrivate::Tab *tab = d->at(index))
1245 return tab->textColor;
1246 return QColor();
1247}
1248
1249/*!
1250 Sets the color of the text in the tab with the given \a index to the specified \a color.
1251
1252 If an invalid color is specified, the tab will use the QTabBar foreground role instead.
1253
1254 \sa tabTextColor()
1255*/
1256void QTabBar::setTabTextColor(int index, const QColor &color)
1257{
1258 Q_D(QTabBar);
1259 if (QTabBarPrivate::Tab *tab = d->at(index)) {
1260 tab->textColor = color;
1261 update(tabRect(index));
1262 }
1263}
1264
1265/*!
1266 Returns the icon of the tab at position \a index, or a null icon
1267 if \a index is out of range.
1268*/
1269QIcon QTabBar::tabIcon(int index) const
1270{
1271 Q_D(const QTabBar);
1272 if (const QTabBarPrivate::Tab *tab = d->at(index))
1273 return tab->icon;
1274 return QIcon();
1275}
1276
1277/*!
1278 Sets the icon of the tab at position \a index to \a icon.
1279*/
1280void QTabBar::setTabIcon(int index, const QIcon & icon)
1281{
1282 Q_D(QTabBar);
1283 if (QTabBarPrivate::Tab *tab = d->at(index)) {
1284 bool simpleIconChange = (!icon.isNull() && !tab->icon.isNull());
1285 tab->icon = icon;
1286 if (simpleIconChange)
1287 update(tabRect(index));
1288 else
1289 d->refresh();
1290 }
1291}
1292
1293#if QT_CONFIG(tooltip)
1294/*!
1295 Sets the tool tip of the tab at position \a index to \a tip.
1296*/
1297void QTabBar::setTabToolTip(int index, const QString & tip)
1298{
1299 Q_D(QTabBar);
1300 if (QTabBarPrivate::Tab *tab = d->at(index))
1301 tab->toolTip = tip;
1302}
1303
1304/*!
1305 Returns the tool tip of the tab at position \a index, or an empty
1306 string if \a index is out of range.
1307*/
1308QString QTabBar::tabToolTip(int index) const
1309{
1310 Q_D(const QTabBar);
1311 if (const QTabBarPrivate::Tab *tab = d->at(index))
1312 return tab->toolTip;
1313 return QString();
1314}
1315#endif // QT_CONFIG(tooltip)
1316
1317#if QT_CONFIG(whatsthis)
1318/*!
1319 \since 4.1
1320
1321 Sets the What's This help text of the tab at position \a index
1322 to \a text.
1323*/
1324void QTabBar::setTabWhatsThis(int index, const QString &text)
1325{
1326 Q_D(QTabBar);
1327 if (QTabBarPrivate::Tab *tab = d->at(index))
1328 tab->whatsThis = text;
1329}
1330
1331/*!
1332 \since 4.1
1333
1334 Returns the What's This help text of the tab at position \a index,
1335 or an empty string if \a index is out of range.
1336*/
1337QString QTabBar::tabWhatsThis(int index) const
1338{
1339 Q_D(const QTabBar);
1340 if (const QTabBarPrivate::Tab *tab = d->at(index))
1341 return tab->whatsThis;
1342 return QString();
1343}
1344
1345#endif // QT_CONFIG(whatsthis)
1346
1347/*!
1348 Sets the data of the tab at position \a index to \a data.
1349*/
1350void QTabBar::setTabData(int index, const QVariant & data)
1351{
1352 Q_D(QTabBar);
1353 if (QTabBarPrivate::Tab *tab = d->at(index))
1354 tab->data = data;
1355}
1356
1357/*!
1358 Returns the data of the tab at position \a index, or a null
1359 variant if \a index is out of range.
1360*/
1361QVariant QTabBar::tabData(int index) const
1362{
1363 Q_D(const QTabBar);
1364 if (const QTabBarPrivate::Tab *tab = d->at(index))
1365 return tab->data;
1366 return QVariant();
1367}
1368
1369/*!
1370 Returns the visual rectangle of the tab at position \a
1371 index, or a null rectangle if \a index is hidden, or out of range.
1372*/
1373QRect QTabBar::tabRect(int index) const
1374{
1375 Q_D(const QTabBar);
1376 if (const QTabBarPrivate::Tab *tab = d->at(index)) {
1377 if (d->layoutDirty)
1378 const_cast<QTabBarPrivate*>(d)->layoutTabs();
1379 if (!tab->visible)
1380 return QRect();
1381 QRect r = tab->rect;
1382 if (verticalTabs(d->shape))
1383 r.translate(0, -d->scrollOffset);
1384 else
1385 r.translate(-d->scrollOffset, 0);
1386 if (!verticalTabs(d->shape))
1387 r = QStyle::visualRect(layoutDirection(), rect(), r);
1388 return r;
1389 }
1390 return QRect();
1391}
1392
1393/*!
1394 \since 4.3
1395 Returns the index of the tab that covers \a position or -1 if no
1396 tab covers \a position;
1397*/
1398
1399int QTabBar::tabAt(const QPoint &position) const
1400{
1401 Q_D(const QTabBar);
1402 if (d->validIndex(d->currentIndex)
1403 && tabRect(d->currentIndex).contains(position)) {
1404 return d->currentIndex;
1405 }
1406 const int max = d->tabList.size();
1407 for (int i = 0; i < max; ++i) {
1408 if (tabRect(i).contains(position)) {
1409 return i;
1410 }
1411 }
1412 return -1;
1413}
1414
1415/*!
1416 \property QTabBar::currentIndex
1417 \brief the index of the tab bar's visible tab
1418
1419 The current index is -1 if there is no current tab.
1420*/
1421
1422int QTabBar::currentIndex() const
1423{
1424 Q_D(const QTabBar);
1425 if (d->validIndex(d->currentIndex))
1426 return d->currentIndex;
1427 return -1;
1428}
1429
1430
1431void QTabBar::setCurrentIndex(int index)
1432{
1433 Q_D(QTabBar);
1434 if (d->dragInProgress && d->pressedIndex != -1)
1435 return;
1436 if (d->currentIndex == index)
1437 return;
1438
1439 int oldIndex = d->currentIndex;
1440 if (auto tab = d->at(index)) {
1441 d->currentIndex = index;
1442 // If the size hint depends on whether the tab is selected (for instance a style
1443 // sheet rule that sets a bold font on the 'selected' tab) then we need to
1444 // re-layout the entire tab bar. To minimize the cost, do that only if the
1445 // size hint changes for the tab that becomes the current tab (the old current tab
1446 // will most certainly do the same). QTBUG-6905
1447 if (tabRect(index).size() != tabSizeHint(index))
1448 d->layoutTabs();
1449 update();
1450 if (!isVisible())
1451 d->layoutDirty = true;
1452 else
1453 d->makeVisible(index);
1454 if (d->validIndex(oldIndex)) {
1455 tab->lastTab = oldIndex;
1456 d->layoutTab(oldIndex);
1457 }
1458 d->layoutTab(index);
1459#if QT_CONFIG(accessibility)
1460 if (QAccessible::isActive()) {
1461 if (hasFocus()) {
1462 QAccessibleEvent focusEvent(this, QAccessible::Focus);
1463 focusEvent.setChild(index);
1464 QAccessible::updateAccessibility(&focusEvent);
1465 }
1466 QAccessibleEvent selectionEvent(this, QAccessible::Selection);
1467 selectionEvent.setChild(index);
1468 QAccessible::updateAccessibility(&selectionEvent);
1469 }
1470#endif
1471 emit currentChanged(index);
1472 }
1473}
1474
1475/*!
1476 \property QTabBar::iconSize
1477 \brief The size for icons in the tab bar
1478 \since 4.1
1479
1480 The default value is style-dependent. \c iconSize is a maximum
1481 size; icons that are smaller are not scaled up.
1482
1483 \sa QTabWidget::iconSize
1484*/
1485QSize QTabBar::iconSize() const
1486{
1487 Q_D(const QTabBar);
1488 if (d->iconSize.isValid())
1489 return d->iconSize;
1490 int iconExtent = style()->pixelMetric(QStyle::PM_TabBarIconSize, nullptr, this);
1491 return QSize(iconExtent, iconExtent);
1492
1493}
1494
1495void QTabBar::setIconSize(const QSize &size)
1496{
1497 Q_D(QTabBar);
1498 d->iconSize = size;
1499 d->layoutDirty = true;
1500 update();
1501 updateGeometry();
1502}
1503
1504/*!
1505 \property QTabBar::count
1506 \brief the number of tabs in the tab bar
1507*/
1508
1509int QTabBar::count() const
1510{
1511 Q_D(const QTabBar);
1512 return d->tabList.size();
1513}
1514
1515
1516/*!\reimp
1517 */
1518QSize QTabBar::sizeHint() const
1519{
1520 Q_D(const QTabBar);
1521 if (d->layoutDirty)
1522 const_cast<QTabBarPrivate*>(d)->layoutTabs();
1523 QRect r;
1524 for (const auto tab : d->tabList) {
1525 if (tab->visible)
1526 r = r.united(tab->maxRect);
1527 }
1528 return r.size();
1529}
1530
1531/*!\reimp
1532 */
1533QSize QTabBar::minimumSizeHint() const
1534{
1535 Q_D(const QTabBar);
1536 if (d->layoutDirty)
1537 const_cast<QTabBarPrivate*>(d)->layoutTabs();
1538 if (!d->useScrollButtons) {
1539 QRect r;
1540 for (const auto tab : d->tabList) {
1541 if (tab->visible)
1542 r = r.united(tab->minRect);
1543 }
1544 return r.size();
1545 }
1546 if (verticalTabs(d->shape))
1547 return QSize(sizeHint().width(), d->rightB->sizeHint().height() * 2 + 75);
1548 else
1549 return QSize(d->rightB->sizeHint().width() * 2 + 75, sizeHint().height());
1550}
1551
1552// Compute the most-elided possible text, for minimumSizeHint
1553static QString computeElidedText(Qt::TextElideMode mode, const QString &text)
1554{
1555 if (text.size() <= 3)
1556 return text;
1557
1558 static const auto Ellipses = "..."_L1;
1559 QString ret;
1560 switch (mode) {
1561 case Qt::ElideRight:
1562 ret = QStringView{text}.left(2) + Ellipses;
1563 break;
1564 case Qt::ElideMiddle:
1565 ret = QStringView{text}.left(1) + Ellipses + QStringView{text}.right(1);
1566 break;
1567 case Qt::ElideLeft:
1568 ret = Ellipses + QStringView{text}.right(2);
1569 break;
1570 case Qt::ElideNone:
1571 ret = text;
1572 break;
1573 }
1574 return ret;
1575}
1576
1577/*!
1578 Returns the minimum tab size hint for the tab at position \a index.
1579 \since 5.0
1580*/
1581
1582QSize QTabBar::minimumTabSizeHint(int index) const
1583{
1584 Q_D(const QTabBar);
1585 QTabBarPrivate::Tab *tab = d->tabList.at(index);
1586 QString oldText = tab->text;
1587 tab->text = computeElidedText(d->elideMode, oldText);
1588 tab->measuringMinimum = true;
1589 QSize size = tabSizeHint(index);
1590 tab->text = oldText;
1591 tab->measuringMinimum = false;
1592 return size;
1593}
1594
1595/*!
1596 Returns the size hint for the tab at position \a index.
1597*/
1598QSize QTabBar::tabSizeHint(int index) const
1599{
1600 //Note: this must match with the computations in QCommonStylePrivate::tabLayout
1601 Q_D(const QTabBar);
1602 if (const QTabBarPrivate::Tab *tab = d->at(index)) {
1603 QStyleOptionTab opt;
1604 d->initBasicStyleOption(&opt, index);
1605 opt.text = tab->text;
1606 QSize iconSize = tab->icon.isNull() ? QSize(0, 0) : opt.iconSize;
1607 int hframe = style()->pixelMetric(QStyle::PM_TabBarTabHSpace, &opt, this);
1608 int vframe = style()->pixelMetric(QStyle::PM_TabBarTabVSpace, &opt, this);
1609
1610 int maxWidgetHeight = qMax(opt.leftButtonSize.height(), opt.rightButtonSize.height());
1611 int maxWidgetWidth = qMax(opt.leftButtonSize.width(), opt.rightButtonSize.width());
1612
1613 int widgetWidth = 0;
1614 int widgetHeight = 0;
1615 int padding = 0;
1616 if (!opt.leftButtonSize.isEmpty()) {
1617 padding += 4;
1618 widgetWidth += opt.leftButtonSize.width();
1619 widgetHeight += opt.leftButtonSize.height();
1620 }
1621 if (!opt.rightButtonSize.isEmpty()) {
1622 padding += 4;
1623 widgetWidth += opt.rightButtonSize.width();
1624 widgetHeight += opt.rightButtonSize.height();
1625 }
1626 if (!opt.icon.isNull())
1627 padding += 4;
1628
1629 auto it = d->textSizes.find(tab->text);
1630 if (it == d->textSizes.end()) {
1631 const QFontMetrics fm = fontMetrics();
1632 it = d->textSizes.insert(tab->text, fm.size(Qt::TextShowMnemonic, tab->text)).first;
1633 }
1634 const int textWidth = it.value().width();
1635 const int textHeight = it.value().height();
1636 QSize csz;
1637 if (verticalTabs(d->shape)) {
1638 csz = QSize(qMax(maxWidgetWidth, qMax(textHeight, iconSize.height())) + vframe,
1639 textWidth + iconSize.width() + hframe + widgetHeight + padding);
1640 } else {
1641 csz = QSize(textWidth + iconSize.width() + hframe + widgetWidth + padding,
1642 qMax(maxWidgetHeight, qMax(textHeight, iconSize.height())) + vframe);
1643 }
1644
1645 QSize retSize = style()->sizeFromContents(QStyle::CT_TabBarTab, &opt, csz, this);
1646 return retSize;
1647 }
1648 return QSize();
1649}
1650
1651/*!
1652 This virtual handler is called after a new tab was added or
1653 inserted at position \a index.
1654
1655 \sa tabRemoved()
1656 */
1657void QTabBar::tabInserted(int index)
1658{
1659 Q_UNUSED(index);
1660}
1661
1662/*!
1663 This virtual handler is called after a tab was removed from
1664 position \a index.
1665
1666 \sa tabInserted()
1667 */
1668void QTabBar::tabRemoved(int index)
1669{
1670 Q_UNUSED(index);
1671}
1672
1673/*!
1674 This virtual handler is called whenever the tab layout changes.
1675
1676 \sa tabRect()
1677 */
1678void QTabBar::tabLayoutChange()
1679{
1680}
1681
1682
1683/*!\reimp
1684 */
1685void QTabBar::showEvent(QShowEvent *)
1686{
1687 Q_D(QTabBar);
1688 if (d->layoutDirty)
1689 d->refresh();
1690 if (!d->validIndex(d->currentIndex))
1691 setCurrentIndex(0);
1692 else
1693 d->makeVisible(d->currentIndex);
1694 d->updateMacBorderMetrics();
1695}
1696
1697/*!\reimp
1698 */
1699void QTabBar::hideEvent(QHideEvent *)
1700{
1701 Q_D(QTabBar);
1702 d->updateMacBorderMetrics();
1703}
1704
1705/*!\reimp
1706 */
1707bool QTabBar::event(QEvent *event)
1708{
1709 Q_D(QTabBar);
1710 switch (event->type()) {
1711 case QEvent::HoverMove:
1712 case QEvent::HoverEnter: {
1713 QHoverEvent *he = static_cast<QHoverEvent *>(event);
1714 d->mousePosition = he->position().toPoint();
1715 const auto sr = d->scrollRect();
1716 const auto oldHoverRect = d->hoverRect & sr;
1717 if (!oldHoverRect.contains(d->mousePosition)) {
1718 if (d->hoverRect.isValid())
1719 update(d->hoverRect);
1720 d->hoverIndex = tabAt(d->mousePosition);
1721 if (d->validIndex(d->hoverIndex) && sr.contains(d->mousePosition)) {
1722 d->hoverRect = tabRect(d->hoverIndex);
1723 update(d->hoverRect);
1724 } else {
1725 d->hoverRect = QRect();
1726 d->hoverIndex = -1;
1727 }
1728 }
1729 return true;
1730 }
1731 case QEvent::HoverLeave: {
1732 d->mousePosition = {-1, -1};
1733 if (d->hoverRect.isValid())
1734 update(d->hoverRect);
1735 d->hoverIndex = -1;
1736 d->hoverRect = QRect();
1737#if QT_CONFIG(wheelevent)
1738 d->accumulatedAngleDelta = QPoint();
1739#endif
1740 return true;
1741 }
1742#if QT_CONFIG(tooltip)
1743 case QEvent::ToolTip:
1744 if (const QTabBarPrivate::Tab *tab = d->at(tabAt(static_cast<QHelpEvent*>(event)->pos()))) {
1745 if (!tab->toolTip.isEmpty()) {
1746 QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), tab->toolTip, this);
1747 return true;
1748 }
1749 }
1750 break;
1751#endif // QT_CONFIG(tooltip)
1752#if QT_CONFIG(whatsthis)
1753 case QEvent::QEvent::QueryWhatsThis: {
1754 const QTabBarPrivate::Tab *tab = d->at(d->indexAtPos(static_cast<QHelpEvent*>(event)->pos()));
1755 if (!tab || tab->whatsThis.isEmpty())
1756 event->ignore();
1757 return true;
1758 }
1759 case QEvent::WhatsThis:
1760 if (const QTabBarPrivate::Tab *tab = d->at(d->indexAtPos(static_cast<QHelpEvent*>(event)->pos()))) {
1761 if (!tab->whatsThis.isEmpty()) {
1762 QWhatsThis::showText(static_cast<QHelpEvent*>(event)->globalPos(),
1763 tab->whatsThis, this);
1764 return true;
1765 }
1766 }
1767 break;
1768#endif // QT_CONFIG(whatsthis)
1769#ifndef QT_NO_SHORTCUT
1770
1771 case QEvent::Shortcut: {
1772 QShortcutEvent *se = static_cast<QShortcutEvent *>(event);
1773 for (int i = 0; i < d->tabList.size(); ++i) {
1774 const QTabBarPrivate::Tab *tab = d->tabList.at(i);
1775 if (tab->shortcutId == se->shortcutId()) {
1776 setCurrentIndex(i);
1777 return true;
1778 }
1779 }
1780 }
1781 break;
1782#endif
1783 case QEvent::Move:
1784 d->updateMacBorderMetrics();
1785 break;
1786#if QT_CONFIG(draganddrop)
1787
1788 case QEvent::DragEnter:
1789 if (d->changeCurrentOnDrag)
1790 event->accept();
1791 break;
1792 case QEvent::DragMove:
1793 if (d->changeCurrentOnDrag) {
1794 const int tabIndex = tabAt(static_cast<QDragMoveEvent *>(event)->position().toPoint());
1795 if (isTabEnabled(tabIndex) && d->switchTabCurrentIndex != tabIndex) {
1796 d->switchTabCurrentIndex = tabIndex;
1797 d->switchTabTimer.start(
1798 style()->styleHint(QStyle::SH_TabBar_ChangeCurrentDelay, nullptr, this) * 1ms, this);
1799 }
1800 event->ignore();
1801 }
1802 break;
1803 case QEvent::DragLeave:
1804 case QEvent::Drop:
1805 d->killSwitchTabTimer();
1806 event->ignore();
1807 break;
1808#endif
1809 case QEvent::MouseButtonPress:
1810 case QEvent::MouseButtonRelease:
1811 case QEvent::MouseMove:
1812 d->mousePosition = static_cast<QMouseEvent *>(event)->position().toPoint();
1813 d->mouseButtons = static_cast<QMouseEvent *>(event)->buttons();
1814 break;
1815 default:
1816 break;
1817 }
1818
1819 return QWidget::event(event);
1820}
1821
1822/*!\reimp
1823 */
1824void QTabBar::resizeEvent(QResizeEvent *)
1825{
1826 Q_D(QTabBar);
1827 if (d->layoutDirty)
1828 updateGeometry();
1829
1830 // when resizing, we want to keep the scroll offset as much as possible
1831 d->layoutTabs();
1832
1833 d->makeVisible(d->currentIndex);
1834}
1835
1836/*!\reimp
1837 */
1838void QTabBar::paintEvent(QPaintEvent *)
1839{
1840 Q_D(QTabBar);
1841
1842 QStyleOptionTabBarBase optTabBase;
1843 QTabBarPrivate::initStyleBaseOption(&optTabBase, this, size());
1844
1845 QStylePainter p(this);
1846 int selected = -1;
1847 int cutLeft = -1;
1848 int cutRight = -1;
1849 bool vertical = verticalTabs(d->shape);
1850 QStyleOptionTab cutTabLeft;
1851 QStyleOptionTab cutTabRight;
1852 selected = d->currentIndex;
1853 if (d->dragInProgress)
1854 selected = d->pressedIndex;
1855 const QRect scrollRect = d->scrollRect();
1856 const QRect normalizedScrollRect = d->normalizedScrollRect();
1857
1858 for (int i = 0; i < d->tabList.size(); ++i)
1859 optTabBase.tabBarRect |= tabRect(i);
1860
1861 optTabBase.selectedTabRect = tabRect(selected);
1862
1863 if (d->drawBase)
1864 p.drawPrimitive(QStyle::PE_FrameTabBarBase, optTabBase);
1865
1866 // the buttons might be semi-transparent or not fill their rect, but we don't
1867 // want the tab underneath to shine through, so clip the button area; QTBUG-50866
1868 if (d->leftB->isVisible() || d->rightB->isVisible()) {
1869 QStyleOption opt;
1870 opt.initFrom(this);
1871 QRegion buttonRegion;
1872 if (d->leftB->isVisible()) {
1873 const auto r = style()->subElementRect(QStyle::SE_TabBarScrollLeftButton, &opt, this);
1874 buttonRegion |= r;
1875 }
1876 if (d->rightB->isVisible()) {
1877 const auto r = style()->subElementRect(QStyle::SE_TabBarScrollRightButton, &opt, this);
1878 buttonRegion |= r;
1879 }
1880 if (!buttonRegion.isEmpty())
1881 p.setClipRegion(QRegion(rect()) - buttonRegion);
1882 }
1883
1884 for (int i = 0; i < d->tabList.size(); ++i) {
1885 const auto tab = d->tabList.at(i);
1886 if (!tab->visible)
1887 continue;
1888 for (const auto side : { QTabBar::LeftSide, QTabBar::RightSide }) {
1889 if (auto closeButton = qobject_cast<CloseButton *>(tabButton(i, side)))
1890 closeButton->setParentClipRect(scrollRect);
1891 }
1892 QStyleOptionTab tabOption;
1893 initStyleOption(&tabOption, i);
1894 if (tab->dragOffset != 0) {
1895 if (vertical) {
1896 tabOption.rect.moveTop(tabOption.rect.y() + tab->dragOffset);
1897 } else {
1898 tabOption.rect.moveLeft(tabOption.rect.x() + tab->dragOffset);
1899 }
1900 }
1901 if (!(tabOption.state & QStyle::State_Enabled)) {
1902 tabOption.palette.setCurrentColorGroup(QPalette::Disabled);
1903 }
1904
1905 // If this tab is partially obscured, make a note of it so that we can pass the information
1906 // along when we draw the tear.
1907 QRect tabRect = tab->rect;
1908 int tabStart = vertical ? tabRect.top() : tabRect.left();
1909 int tabEnd = vertical ? tabRect.bottom() : tabRect.right();
1910 if (tabStart < normalizedScrollRect.left() + d->scrollOffset) {
1911 cutLeft = i;
1912 cutTabLeft = tabOption;
1913 } else if (tabEnd > normalizedScrollRect.right() + d->scrollOffset) {
1914 cutRight = i;
1915 cutTabRight = tabOption;
1916 }
1917
1918 // Don't bother drawing a tab if the entire tab is outside of the visible tab bar.
1919 if ((!vertical && (tabOption.rect.right() < 0 || tabOption.rect.left() > width()))
1920 || (vertical && (tabOption.rect.bottom() < 0 || tabOption.rect.top() > height())))
1921 continue;
1922
1923 optTabBase.tabBarRect |= tabOption.rect;
1924 if (i == selected)
1925 continue;
1926
1927 p.drawControl(QStyle::CE_TabBarTab, tabOption);
1928 }
1929
1930 // Draw the selected tab last to get it "on top"
1931 if (selected >= 0) {
1932 QStyleOptionTab tabOption;
1933 const auto tab = d->tabList.at(selected);
1934 initStyleOption(&tabOption, selected);
1935
1936 if (tab->dragOffset != 0) {
1937 // if the drag offset is != 0, a move is in progress (drag or animation)
1938 // => set the tab position to Moving to preserve the rect
1939 tabOption.position = QStyleOptionTab::TabPosition::Moving;
1940
1941 if (vertical)
1942 tabOption.rect.moveTop(tabOption.rect.y() + tab->dragOffset);
1943 else
1944 tabOption.rect.moveLeft(tabOption.rect.x() + tab->dragOffset);
1945 }
1946
1947 // Calculate the rect of a moving tab
1948 const int taboverlap = style()->pixelMetric(QStyle::PM_TabBarTabOverlap, nullptr, this);
1949 const QRect &movingRect = verticalTabs(d->shape)
1950 ? tabOption.rect.adjusted(0, -taboverlap, 0, taboverlap)
1951 : tabOption.rect.adjusted(-taboverlap, 0, taboverlap, 0);
1952
1953 // If a drag is in process, set the moving tab's geometry here
1954 // (in an animation, it is already set)
1955 if (d->dragInProgress)
1956 d->movingTab->setGeometry(movingRect);
1957
1958 p.drawControl(QStyle::CE_TabBarTab, tabOption);
1959 }
1960
1961 // Only draw the tear indicator if necessary. Most of the time we don't need too.
1962 if (d->leftB->isVisible() && cutLeft >= 0) {
1963 cutTabLeft.rect = rect();
1964 cutTabLeft.rect = style()->subElementRect(QStyle::SE_TabBarTearIndicatorLeft, &cutTabLeft, this);
1965 p.drawPrimitive(QStyle::PE_IndicatorTabTearLeft, cutTabLeft);
1966 }
1967
1968 if (d->rightB->isVisible() && cutRight >= 0) {
1969 cutTabRight.rect = rect();
1970 cutTabRight.rect = style()->subElementRect(QStyle::SE_TabBarTearIndicatorRight, &cutTabRight, this);
1971 p.drawPrimitive(QStyle::PE_IndicatorTabTearRight, cutTabRight);
1972 }
1973}
1974
1975/*
1976 When index changes visibility, we have to find first & last visible indexes.
1977 If remove is set, we force both
1978 */
1979void QTabBarPrivate::calculateFirstLastVisible(int index, bool visible, bool remove)
1980{
1981 if (visible) {
1982 firstVisible = qMin(index, firstVisible);
1983 lastVisible = qMax(index, lastVisible);
1984 } else {
1985 if (remove || (index == firstVisible)) {
1986 firstVisible = -1;
1987 for (int i = 0; i < tabList.size(); ++i) {
1988 if (tabList.at(i)->visible) {
1989 firstVisible = i;
1990 break;
1991 }
1992 }
1993 }
1994 if (remove || (index == lastVisible)) {
1995 lastVisible = -1;
1996 for (int i = tabList.size() - 1; i >= 0; --i) {
1997 if (tabList.at(i)->visible) {
1998 lastVisible = i;
1999 break;
2000 }
2001 }
2002 }
2003 }
2004}
2005
2006/*
2007 Selects the new current index starting at "fromIndex". If "fromIndex" is visible we're done.
2008 Else it tries any index AFTER fromIndex, then any BEFORE fromIndex and, if everything fails,
2009 it returns -1 indicating that no index is available
2010 */
2011int QTabBarPrivate::selectNewCurrentIndexFrom(int fromIndex)
2012{
2013 int newindex = -1;
2014 for (int i = fromIndex; i < tabList.size(); ++i) {
2015 if (at(i)->visible && at(i)->enabled) {
2016 newindex = i;
2017 break;
2018 }
2019 }
2020 if (newindex < 0) {
2021 for (int i = fromIndex-1; i > -1; --i) {
2022 if (at(i)->visible && at(i)->enabled) {
2023 newindex = i;
2024 break;
2025 }
2026 }
2027 }
2028
2029 return newindex;
2030}
2031
2032/*
2033 Given that index at position from moved to position to where return where index goes.
2034 */
2035int QTabBarPrivate::calculateNewPosition(int from, int to, int index) const
2036{
2037 if (index == from)
2038 return to;
2039
2040 int start = qMin(from, to);
2041 int end = qMax(from, to);
2042 if (index >= start && index <= end)
2043 index += (from < to) ? -1 : 1;
2044 return index;
2045}
2046
2047/*!
2048 Moves the item at index position \a from to index position \a to.
2049 \since 4.5
2050
2051 \sa tabMoved(), tabLayoutChange()
2052 */
2053void QTabBar::moveTab(int from, int to)
2054{
2055 Q_D(QTabBar);
2056 if (from == to
2057 || !d->validIndex(from)
2058 || !d->validIndex(to))
2059 return;
2060
2061 auto &fromTab = *d->tabList.at(from);
2062 auto &toTab = *d->tabList.at(to);
2063
2064 bool vertical = verticalTabs(d->shape);
2065 int oldPressedPosition = 0;
2066 if (d->pressedIndex != -1) {
2067 // Record the position of the pressed tab before reordering the tabs.
2068 oldPressedPosition = vertical ? d->tabList.at(d->pressedIndex)->rect.y()
2069 : d->tabList.at(d->pressedIndex)->rect.x();
2070 }
2071
2072 // Update the locations of the tabs first
2073 int start = qMin(from, to);
2074 int end = qMax(from, to);
2075 int width = vertical ? fromTab.rect.height() : fromTab.rect.width();
2076 if (from < to)
2077 width *= -1;
2078 bool rtl = isRightToLeft();
2079 for (int i = start; i <= end; ++i) {
2080 if (i == from)
2081 continue;
2082 auto &tab = *d->tabList.at(i);
2083 if (vertical)
2084 tab.rect.moveTop(tab.rect.y() + width);
2085 else
2086 tab.rect.moveLeft(tab.rect.x() + width);
2087 int direction = -1;
2088 if (rtl && !vertical)
2089 direction *= -1;
2090 if (tab.dragOffset != 0)
2091 tab.dragOffset += (direction * width);
2092 }
2093
2094 if (vertical) {
2095 if (from < to)
2096 fromTab.rect.moveTop(toTab.rect.bottom() + 1);
2097 else
2098 fromTab.rect.moveTop(toTab.rect.top() - width);
2099 } else {
2100 if (from < to)
2101 fromTab.rect.moveLeft(toTab.rect.right() + 1);
2102 else
2103 fromTab.rect.moveLeft(toTab.rect.left() - width);
2104 }
2105
2106 // Move the actual data structures
2107 d->tabList.move(from, to);
2108
2109 // update lastTab locations
2110 for (const auto tab : std::as_const(d->tabList))
2111 tab->lastTab = d->calculateNewPosition(from, to, tab->lastTab);
2112
2113 // update external variables
2114 int previousIndex = d->currentIndex;
2115 d->currentIndex = d->calculateNewPosition(from, to, d->currentIndex);
2116
2117 // If we are in the middle of a drag update the dragStartPosition
2118 if (d->pressedIndex != -1) {
2119 d->pressedIndex = d->calculateNewPosition(from, to, d->pressedIndex);
2120 const auto pressedTab = d->tabList.at(d->pressedIndex);
2121 int newPressedPosition = vertical ? pressedTab->rect.top() : pressedTab->rect.left();
2122 int diff = oldPressedPosition - newPressedPosition;
2123 if (isRightToLeft() && !vertical)
2124 diff *= -1;
2125 if (vertical)
2126 d->dragStartPosition.setY(d->dragStartPosition.y() - diff);
2127 else
2128 d->dragStartPosition.setX(d->dragStartPosition.x() - diff);
2129 }
2130
2131 d->layoutWidgets(start);
2132 update();
2133 emit tabMoved(from, to);
2134 if (previousIndex != d->currentIndex)
2135 emit currentChanged(d->currentIndex);
2136 emit tabLayoutChange();
2137}
2138
2139void QTabBarPrivate::slide(int from, int to)
2140{
2141 Q_Q(QTabBar);
2142 if (from == to
2143 || !validIndex(from)
2144 || !validIndex(to))
2145 return;
2146 bool vertical = verticalTabs(shape);
2147 int preLocation = vertical ? q->tabRect(from).y() : q->tabRect(from).x();
2148 q->setUpdatesEnabled(false);
2149 q->moveTab(from, to);
2150 q->setUpdatesEnabled(true);
2151 int postLocation = vertical ? q->tabRect(to).y() : q->tabRect(to).x();
2152 int length = postLocation - preLocation;
2153 tabList.at(to)->dragOffset -= length;
2154 tabList.at(to)->startAnimation(this, ANIMATION_DURATION);
2155}
2156
2157void QTabBarPrivate::moveTab(int index, int offset)
2158{
2159 if (!validIndex(index))
2160 return;
2161 tabList.at(index)->dragOffset = offset;
2162 layoutTab(index); // Make buttons follow tab
2163 q_func()->update();
2164}
2165
2166/*!\reimp
2167*/
2168void QTabBar::mousePressEvent(QMouseEvent *event)
2169{
2170 Q_D(QTabBar);
2171
2172 const QPoint pos = event->position().toPoint();
2173 const bool isEventInCornerButtons = (!d->leftB->isHidden() && d->leftB->geometry().contains(pos))
2174 || (!d->rightB->isHidden() && d->rightB->geometry().contains(pos));
2175 if (!isEventInCornerButtons) {
2176 const int index = d->indexAtPos(pos);
2177 emit tabBarClicked(index);
2178 }
2179
2180 if (event->button() != Qt::LeftButton) {
2181 event->ignore();
2182 return;
2183 }
2184 // Be safe!
2185 if (d->pressedIndex != -1 && d->movable)
2186 d->moveTabFinished(d->pressedIndex);
2187
2188 d->pressedIndex = d->indexAtPos(event->position().toPoint());
2189
2190 if (d->validIndex(d->pressedIndex)) {
2191 QStyleOptionTabBarBase optTabBase;
2192 optTabBase.initFrom(this);
2193 optTabBase.documentMode = d->documentMode;
2194 if (event->type() == style()->styleHint(QStyle::SH_TabBar_SelectMouseType, &optTabBase, this))
2195 setCurrentIndex(d->pressedIndex);
2196 else
2197 repaint(tabRect(d->pressedIndex));
2198 if (d->movable) {
2199 d->dragStartPosition = event->position().toPoint();
2200 }
2201 }
2202}
2203
2204/*!\reimp
2205 */
2206void QTabBar::mouseMoveEvent(QMouseEvent *event)
2207{
2208 Q_D(QTabBar);
2209 if (d->movable) {
2210 // Be safe!
2211 if (d->pressedIndex != -1
2212 && event->buttons() == Qt::NoButton)
2213 d->moveTabFinished(d->pressedIndex);
2214
2215 // Start drag
2216 if (!d->dragInProgress && d->pressedIndex != -1) {
2217 if ((event->position().toPoint() - d->dragStartPosition).manhattanLength() > QApplication::startDragDistance()) {
2218 d->dragInProgress = true;
2219 d->setupMovableTab();
2220 }
2221 }
2222
2223 if (event->buttons() == Qt::LeftButton
2224 && d->dragInProgress
2225 && d->validIndex(d->pressedIndex)) {
2226 bool vertical = verticalTabs(d->shape);
2227 int dragDistance;
2228 if (vertical) {
2229 dragDistance = (event->position().toPoint().y() - d->dragStartPosition.y());
2230 } else {
2231 dragDistance = (event->position().toPoint().x() - d->dragStartPosition.x());
2232 }
2233 d->tabList.at(d->pressedIndex)->dragOffset = dragDistance;
2234
2235 QRect startingRect = tabRect(d->pressedIndex);
2236 if (vertical)
2237 startingRect.moveTop(startingRect.y() + dragDistance);
2238 else
2239 startingRect.moveLeft(startingRect.x() + dragDistance);
2240
2241 int overIndex;
2242 if (dragDistance < 0)
2243 overIndex = tabAt(startingRect.topLeft());
2244 else
2245 overIndex = tabAt(startingRect.topRight());
2246
2247 if (overIndex != d->pressedIndex && overIndex != -1) {
2248 int offset = 1;
2249 if (isRightToLeft() && !vertical)
2250 offset *= -1;
2251 if (dragDistance < 0) {
2252 dragDistance *= -1;
2253 offset *= -1;
2254 }
2255 for (int i = d->pressedIndex;
2256 offset > 0 ? i < overIndex : i > overIndex;
2257 i += offset) {
2258 QRect overIndexRect = tabRect(overIndex);
2259 int needsToBeOver = (vertical ? overIndexRect.height() : overIndexRect.width()) / 2;
2260 if (dragDistance > needsToBeOver)
2261 d->slide(i + offset, d->pressedIndex);
2262 }
2263 }
2264 // Buttons needs to follow the dragged tab
2265 if (d->pressedIndex != -1)
2266 d->layoutTab(d->pressedIndex);
2267
2268 update();
2269 }
2270 }
2271
2272 if (event->buttons() != Qt::LeftButton) {
2273 event->ignore();
2274 return;
2275 }
2276}
2277
2278void QTabBarPrivate::setupMovableTab()
2279{
2280 Q_Q(QTabBar);
2281 if (!movingTab)
2282 movingTab = new QMovableTabWidget(q);
2283
2284 int taboverlap = q->style()->pixelMetric(QStyle::PM_TabBarTabOverlap, nullptr ,q);
2285 QRect grabRect = q->tabRect(pressedIndex);
2286 if (verticalTabs(shape))
2287 grabRect.adjust(0, -taboverlap, 0, taboverlap);
2288 else
2289 grabRect.adjust(-taboverlap, 0, taboverlap, 0);
2290
2291 QPixmap grabImage(grabRect.size() * q->devicePixelRatio());
2292 grabImage.setDevicePixelRatio(q->devicePixelRatio());
2293 grabImage.fill(Qt::transparent);
2294 QStylePainter p(&grabImage, q);
2295
2296 QStyleOptionTab tab;
2297 q->initStyleOption(&tab, pressedIndex);
2298 tab.position = QStyleOptionTab::Moving;
2299 if (verticalTabs(shape))
2300 tab.rect.moveTopLeft(QPoint(0, taboverlap));
2301 else
2302 tab.rect.moveTopLeft(QPoint(taboverlap, 0));
2303 p.drawControl(QStyle::CE_TabBarTab, tab);
2304 p.end();
2305
2306 movingTab->setPixmap(grabImage);
2307 movingTab->setGeometry(grabRect);
2308 movingTab->raise();
2309
2310 // Re-arrange widget order to avoid overlaps
2311 const auto &pressedTab = *tabList.at(pressedIndex);
2312 if (pressedTab.leftWidget)
2313 pressedTab.leftWidget->raise();
2314 if (pressedTab.rightWidget)
2315 pressedTab.rightWidget->raise();
2316 if (leftB)
2317 leftB->raise();
2318 if (rightB)
2319 rightB->raise();
2320 movingTab->setVisible(true);
2321}
2322
2323void QTabBarPrivate::moveTabFinished(int index)
2324{
2325 Q_Q(QTabBar);
2326 bool cleanup = (pressedIndex == index) || (pressedIndex == -1) || !validIndex(index);
2327 bool allAnimationsFinished = true;
2328#if QT_CONFIG(animation)
2329 for (const auto tab : std::as_const(tabList)) {
2330 if (tab->animation && tab->animation->state() == QAbstractAnimation::Running) {
2331 allAnimationsFinished = false;
2332 break;
2333 }
2334 }
2335#endif // animation
2336 if (allAnimationsFinished && cleanup) {
2337 if (movingTab)
2338 movingTab->setVisible(false); // We might not get a mouse release
2339 for (auto tab : std::as_const(tabList)) {
2340 tab->dragOffset = 0;
2341 }
2342 if (pressedIndex != -1 && movable) {
2343 pressedIndex = -1;
2344 dragInProgress = false;
2345 dragStartPosition = QPoint();
2346 }
2347 layoutWidgets();
2348 } else {
2349 if (!validIndex(index))
2350 return;
2351 tabList.at(index)->dragOffset = 0;
2352 }
2353 q->update();
2354}
2355
2356/*!\reimp
2357*/
2358void QTabBar::mouseReleaseEvent(QMouseEvent *event)
2359{
2360 Q_D(QTabBar);
2361
2362 if (d->closeButtonOnTabs && event->button() == Qt::MiddleButton) {
2363 const int index = tabAt(event->pos());
2364 if (index != -1) {
2365 emit tabCloseRequested(index);
2366 return;
2367 }
2368 }
2369
2370 if (event->button() != Qt::LeftButton) {
2371 event->ignore();
2372 return;
2373 }
2374
2375 if (d->movable && d->dragInProgress && d->validIndex(d->pressedIndex)) {
2376 int length = d->tabList.at(d->pressedIndex)->dragOffset;
2377 int width = verticalTabs(d->shape)
2378 ? tabRect(d->pressedIndex).height()
2379 : tabRect(d->pressedIndex).width();
2380 int duration = qMin(ANIMATION_DURATION,
2381 (qAbs(length) * ANIMATION_DURATION) / width);
2382 d->tabList.at(d->pressedIndex)->startAnimation(d, duration);
2383 d->dragInProgress = false;
2384 d->movingTab->setVisible(false);
2385 d->dragStartPosition = QPoint();
2386 }
2387
2388 // mouse release event might happen outside the tab, so keep the pressed index
2389 int oldPressedIndex = d->pressedIndex;
2390 int i = d->indexAtPos(event->position().toPoint()) == d->pressedIndex ? d->pressedIndex : -1;
2391 d->pressedIndex = -1;
2392 QStyleOptionTabBarBase optTabBase;
2393 optTabBase.initFrom(this);
2394 optTabBase.documentMode = d->documentMode;
2395 const bool selectOnRelease =
2396 (style()->styleHint(QStyle::SH_TabBar_SelectMouseType, &optTabBase, this) == QEvent::MouseButtonRelease);
2397 if (selectOnRelease)
2398 setCurrentIndex(i);
2399 if (d->validIndex(oldPressedIndex))
2400 update(tabRect(oldPressedIndex));
2401}
2402
2403/*!\reimp
2404 */
2405void QTabBar::mouseDoubleClickEvent(QMouseEvent *event)
2406{
2407 Q_D(QTabBar);
2408 const QPoint pos = event->position().toPoint();
2409 const bool isEventInCornerButtons = (!d->leftB->isHidden() && d->leftB->geometry().contains(pos))
2410 || (!d->rightB->isHidden() && d->rightB->geometry().contains(pos));
2411 if (!isEventInCornerButtons)
2412 emit tabBarDoubleClicked(tabAt(pos));
2413
2414 mousePressEvent(event);
2415}
2416
2417/*!\reimp
2418 */
2419void QTabBar::keyPressEvent(QKeyEvent *event)
2420{
2421 Q_D(QTabBar);
2422 if (event->key() != Qt::Key_Left && event->key() != Qt::Key_Right) {
2423 event->ignore();
2424 return;
2425 }
2426 int offset = event->key() == (isRightToLeft() ? Qt::Key_Right : Qt::Key_Left) ? -1 : 1;
2427 d->setCurrentNextEnabledIndex(offset);
2428}
2429
2430/*!\reimp
2431 */
2432#if QT_CONFIG(wheelevent)
2433void QTabBar::wheelEvent(QWheelEvent *event)
2434{
2435 Q_D(QTabBar);
2436 if (style()->styleHint(QStyle::SH_TabBar_AllowWheelScrolling, nullptr, this)) {
2437 const bool wheelVertical = qAbs(event->angleDelta().y()) > qAbs(event->angleDelta().x());
2438 const bool tabsVertical = verticalTabs(d->shape);
2439 if (event->device()->capabilities().testFlag(QInputDevice::Capability::PixelScroll)) {
2440 // For wheels/touch pads with pixel precision, scroll the tab bar if
2441 // it has the right orientation.
2442 int delta = 0;
2443 if (tabsVertical == wheelVertical)
2444 delta = wheelVertical ? event->pixelDelta().y() : event->pixelDelta().x();
2445 if (!tabsVertical && layoutDirection() == Qt::RightToLeft)
2446 delta = -delta;
2447 if (delta && d->validIndex(d->lastVisible)) {
2448 const int oldScrollOffset = d->scrollOffset;
2449 const QRect lastTabRect = d->tabList.at(d->lastVisible)->rect;
2450 const QRect scrollRect = d->normalizedScrollRect(d->lastVisible);
2451 int scrollRectExtent = scrollRect.right();
2452 if (!d->leftB->isVisible())
2453 scrollRectExtent += tabsVertical ? d->leftB->height() : d->leftB->width();
2454 if (!d->rightB->isVisible())
2455 scrollRectExtent += tabsVertical ? d->rightB->height() : d->rightB->width();
2456
2457 const QRect scrollRect0 = d->normalizedScrollRect(0);
2458 const int minScrollOffset = -1 * scrollRect0.left();
2459 const int maxScrollOffset = qMax((tabsVertical ?
2460 lastTabRect.bottom() :
2461 lastTabRect.right()) - scrollRectExtent, 0);
2462 d->scrollOffset = qBound(minScrollOffset, d->scrollOffset - delta, maxScrollOffset);
2463 d->leftB->setEnabled(d->scrollOffset > -scrollRect.left());
2464 d->rightB->setEnabled(maxScrollOffset > d->scrollOffset);
2465 if (oldScrollOffset != d->scrollOffset) {
2466 event->accept();
2467 d->layoutTabs();
2468 update();
2469 return;
2470 }
2471 }
2472 } else {
2473 d->accumulatedAngleDelta += event->angleDelta();
2474 const int xSteps = d->accumulatedAngleDelta.x() / QWheelEvent::DefaultDeltasPerStep;
2475 const int ySteps = d->accumulatedAngleDelta.y() / QWheelEvent::DefaultDeltasPerStep;
2476 int offset = 0;
2477 if (xSteps > 0 || ySteps > 0) {
2478 offset = -1;
2479 d->accumulatedAngleDelta = QPoint();
2480 } else if (xSteps < 0 || ySteps < 0) {
2481 offset = 1;
2482 d->accumulatedAngleDelta = QPoint();
2483 }
2484 const int oldCurrentIndex = d->currentIndex;
2485 d->setCurrentNextEnabledIndex(offset);
2486 // Applying scroll events perpendicular to the tab bar's orientation:
2487 // - is a hack, but required to make (very common) horizontal tab bars work with
2488 // (very common) vertical scroll wheels
2489 // - causes surprising behavior when the tab bar scrolls away after the tab
2490 // index reaches an end stop - so always eat "perpendicular events"
2491 // Forwarding "parallel events" is less surprising and may help to scroll the
2492 // desired part of the tab bar into view when it's inside a scroll view.
2493 if (wheelVertical != tabsVertical || oldCurrentIndex != d->currentIndex) {
2494 event->accept();
2495 return;
2496 }
2497 }
2498 QWidget::wheelEvent(event);
2499 }
2500}
2501#endif // QT_CONFIG(wheelevent)
2502
2503void QTabBarPrivate::setCurrentNextEnabledIndex(int offset)
2504{
2505 Q_Q(QTabBar);
2506 for (int index = currentIndex + offset; validIndex(index); index += offset) {
2507 if (tabList.at(index)->enabled && tabList.at(index)->visible) {
2508 q->setCurrentIndex(index);
2509 break;
2510 }
2511 }
2512}
2513
2514/*!\reimp
2515 */
2516void QTabBar::changeEvent(QEvent *event)
2517{
2518 Q_D(QTabBar);
2519 switch (event->type()) {
2520 case QEvent::StyleChange:
2521 if (!d->elideModeSetByUser)
2522 d->elideMode = Qt::TextElideMode(style()->styleHint(QStyle::SH_TabBar_ElideMode, nullptr, this));
2523 if (!d->useScrollButtonsSetByUser)
2524 d->useScrollButtons = !style()->styleHint(QStyle::SH_TabBar_PreferNoArrows, nullptr, this);
2525 Q_FALLTHROUGH();
2526 case QEvent::FontChange:
2527 d->textSizes.clear();
2528 d->refresh();
2529 break;
2530 default:
2531 break;
2532 }
2533
2534 QWidget::changeEvent(event);
2535}
2536
2537/*!
2538 \reimp
2539*/
2540void QTabBar::timerEvent(QTimerEvent *event)
2541{
2542 Q_D(QTabBar);
2543 if (event->id() == d->switchTabTimer.id()) {
2544 d->switchTabTimer.stop();
2545 setCurrentIndex(d->switchTabCurrentIndex);
2546 d->switchTabCurrentIndex = -1;
2547 }
2548 QWidget::timerEvent(event);
2549}
2550
2551/*!
2552 \property QTabBar::elideMode
2553 \brief how to elide text in the tab bar
2554 \since 4.2
2555
2556 This property controls how items are elided when there is not
2557 enough space to show them for a given tab bar size.
2558
2559 By default the value is style-dependent.
2560
2561 \sa QTabWidget::elideMode, usesScrollButtons, QStyle::SH_TabBar_ElideMode
2562*/
2563
2564Qt::TextElideMode QTabBar::elideMode() const
2565{
2566 Q_D(const QTabBar);
2567 return d->elideMode;
2568}
2569
2570void QTabBar::setElideMode(Qt::TextElideMode mode)
2571{
2572 Q_D(QTabBar);
2573 d->elideMode = mode;
2574 d->elideModeSetByUser = true;
2575 d->textSizes.clear();
2576 d->refresh();
2577}
2578
2579/*!
2580 \property QTabBar::usesScrollButtons
2581 \brief Whether or not a tab bar should use buttons to scroll tabs when it
2582 has many tabs.
2583 \since 4.2
2584
2585 When there are too many tabs in a tab bar for its size, the tab bar can either choose
2586 to expand its size or to add buttons that allow you to scroll through the tabs.
2587
2588 By default the value is style-dependent.
2589
2590 \sa elideMode, QTabWidget::usesScrollButtons, QStyle::SH_TabBar_PreferNoArrows
2591*/
2592bool QTabBar::usesScrollButtons() const
2593{
2594 return d_func()->useScrollButtons;
2595}
2596
2597void QTabBar::setUsesScrollButtons(bool useButtons)
2598{
2599 Q_D(QTabBar);
2600 d->useScrollButtonsSetByUser = true;
2601 if (d->useScrollButtons == useButtons)
2602 return;
2603 d->useScrollButtons = useButtons;
2604 d->refresh();
2605}
2606
2607/*!
2608 \property QTabBar::tabsClosable
2609 \brief Whether or not a tab bar should place close buttons on each tab
2610 \since 4.5
2611
2612 When tabsClosable is set to true a close button will appear on the tab on
2613 either the left or right hand side depending upon the style. When the button
2614 is clicked directly, or a mouse middle-click is received anywhere in the tab,
2615 the signal tabCloseRequested will be emitted.
2616
2617 By default the value is false.
2618
2619 \sa setTabButton(), tabRemoved()
2620*/
2621
2622bool QTabBar::tabsClosable() const
2623{
2624 Q_D(const QTabBar);
2625 return d->closeButtonOnTabs;
2626}
2627
2628void QTabBar::setTabsClosable(bool closable)
2629{
2630 Q_D(QTabBar);
2631 if (d->closeButtonOnTabs == closable)
2632 return;
2633 d->closeButtonOnTabs = closable;
2634 ButtonPosition closeSide = (ButtonPosition)style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, nullptr, this);
2635 if (!closable) {
2636 for (auto tab : std::as_const(d->tabList)) {
2637 if (closeSide == LeftSide && tab->leftWidget) {
2638 tab->leftWidget->deleteLater();
2639 tab->leftWidget = nullptr;
2640 }
2641 if (closeSide == RightSide && tab->rightWidget) {
2642 tab->rightWidget->deleteLater();
2643 tab->rightWidget = nullptr;
2644 }
2645 }
2646 } else {
2647 bool newButtons = false;
2648 for (int i = 0; i < d->tabList.size(); ++i) {
2649 if (tabButton(i, closeSide))
2650 continue;
2651 newButtons = true;
2652 QAbstractButton *closeButton = new CloseButton(this);
2653 QObjectPrivate::connect(closeButton, &CloseButton::clicked,
2654 d, &QTabBarPrivate::closeTab);
2655 setTabButton(i, closeSide, closeButton);
2656 }
2657 if (newButtons)
2658 d->layoutTabs();
2659 }
2660 update();
2661}
2662
2663/*!
2664 \enum QTabBar::ButtonPosition
2665 \since 4.5
2666
2667 This enum type lists the location of the widget on a tab.
2668
2669 \value LeftSide Left side of the tab.
2670
2671 \value RightSide Right side of the tab.
2672
2673*/
2674
2675/*!
2676 \enum QTabBar::SelectionBehavior
2677 \since 4.5
2678
2679 This enum type lists the behavior of QTabBar when a tab is removed
2680 and the tab being removed is also the current tab.
2681
2682 \value SelectLeftTab Select the tab to the left of the one being removed.
2683
2684 \value SelectRightTab Select the tab to the right of the one being removed.
2685
2686 \value SelectPreviousTab Select the previously selected tab.
2687
2688*/
2689
2690/*!
2691 \property QTabBar::selectionBehaviorOnRemove
2692 \brief What tab should be set as current when removeTab is called if
2693 the removed tab is also the current tab.
2694 \since 4.5
2695
2696 By default the value is SelectRightTab.
2697
2698 \sa removeTab()
2699*/
2700
2701
2702QTabBar::SelectionBehavior QTabBar::selectionBehaviorOnRemove() const
2703{
2704 Q_D(const QTabBar);
2705 return d->selectionBehaviorOnRemove;
2706}
2707
2708void QTabBar::setSelectionBehaviorOnRemove(QTabBar::SelectionBehavior behavior)
2709{
2710 Q_D(QTabBar);
2711 d->selectionBehaviorOnRemove = behavior;
2712}
2713
2714/*!
2715 \property QTabBar::expanding
2716 \brief When expanding is true QTabBar will expand the tabs to use the empty space.
2717 \since 4.5
2718
2719 By default the value is true.
2720
2721 \sa QTabWidget::documentMode
2722*/
2723
2724bool QTabBar::expanding() const
2725{
2726 Q_D(const QTabBar);
2727 return d->expanding;
2728}
2729
2730void QTabBar::setExpanding(bool enabled)
2731{
2732 Q_D(QTabBar);
2733 if (d->expanding == enabled)
2734 return;
2735 d->expanding = enabled;
2736 d->layoutTabs();
2737}
2738
2739/*!
2740 \property QTabBar::movable
2741 \brief This property holds whether the user can move the tabs
2742 within the tabbar area.
2743
2744 \since 4.5
2745
2746 By default, this property is \c false;
2747*/
2748
2749bool QTabBar::isMovable() const
2750{
2751 Q_D(const QTabBar);
2752 return d->movable;
2753}
2754
2755void QTabBar::setMovable(bool movable)
2756{
2757 Q_D(QTabBar);
2758 d->movable = movable;
2759}
2760
2761
2762/*!
2763 \property QTabBar::documentMode
2764 \brief Whether or not the tab bar is rendered in a mode suitable for the main window.
2765 \since 4.5
2766
2767 This property is used as a hint for styles to draw the tabs in a different
2768 way then they would normally look in a tab widget. On \macos this will
2769 look similar to the tabs in Safari or Sierra's Terminal.app.
2770
2771 \sa QTabWidget::documentMode
2772*/
2773bool QTabBar::documentMode() const
2774{
2775 return d_func()->documentMode;
2776}
2777
2778void QTabBar::setDocumentMode(bool enabled)
2779{
2780 Q_D(QTabBar);
2781
2782 d->documentMode = enabled;
2783 d->updateMacBorderMetrics();
2784}
2785
2786/*!
2787 \property QTabBar::autoHide
2788 \brief If true, the tab bar is automatically hidden when it contains less
2789 than 2 tabs.
2790 \since 5.4
2791
2792 By default, this property is false.
2793
2794 \sa QWidget::visible
2795*/
2796
2797bool QTabBar::autoHide() const
2798{
2799 Q_D(const QTabBar);
2800 return d->autoHide;
2801}
2802
2803void QTabBar::setAutoHide(bool hide)
2804{
2805 Q_D(QTabBar);
2806 if (d->autoHide == hide)
2807 return;
2808
2809 d->autoHide = hide;
2810 if (hide)
2811 d->autoHideTabs();
2812 else
2813 setVisible(true);
2814}
2815
2816/*!
2817 \property QTabBar::changeCurrentOnDrag
2818 \brief If true, then the current tab is automatically changed when dragging
2819 over the tabbar.
2820 \since 5.4
2821
2822 \note You should also set acceptDrops property to true to make this feature
2823 work.
2824
2825 By default, this property is false.
2826*/
2827
2828bool QTabBar::changeCurrentOnDrag() const
2829{
2830 Q_D(const QTabBar);
2831 return d->changeCurrentOnDrag;
2832}
2833
2834void QTabBar::setChangeCurrentOnDrag(bool change)
2835{
2836 Q_D(QTabBar);
2837 d->changeCurrentOnDrag = change;
2838 if (!change)
2839 d->killSwitchTabTimer();
2840}
2841
2842/*!
2843 Sets \a widget on the tab \a index. The widget is placed
2844 on the left or right hand side depending on the \a position.
2845 \since 4.5
2846
2847 Any previously set widget in \a position is hidden. Setting \a widget
2848 to \nullptr will hide the current widget at \a position.
2849
2850 The tab bar will take ownership of the widget and so all widgets set here
2851 will be deleted by the tab bar when it is destroyed unless you separately
2852 reparent the widget after setting some other widget (or \nullptr).
2853
2854 \sa tabsClosable()
2855 */
2856void QTabBar::setTabButton(int index, ButtonPosition position, QWidget *widget)
2857{
2858 Q_D(QTabBar);
2859 if (index < 0 || index >= d->tabList.size())
2860 return;
2861 if (widget) {
2862 widget->setParent(this);
2863 // make sure our left and right widgets stay on top
2864 widget->lower();
2865 widget->show();
2866 }
2867 auto &tab = *d->tabList.at(index);
2868 if (position == LeftSide) {
2869 if (tab.leftWidget)
2870 tab.leftWidget->hide();
2871 tab.leftWidget = widget;
2872 } else {
2873 if (tab.rightWidget)
2874 tab.rightWidget->hide();
2875 tab.rightWidget = widget;
2876 }
2877 d->layoutTabs();
2878 d->refresh();
2879 update();
2880}
2881
2882/*!
2883 Returns the widget set a tab \a index and \a position or \nullptr
2884 if one is not set.
2885 */
2886QWidget *QTabBar::tabButton(int index, ButtonPosition position) const
2887{
2888 Q_D(const QTabBar);
2889 if (const auto tab = d->at(index)) {
2890 return position == LeftSide ? tab->leftWidget
2891 : tab->rightWidget;
2892 }
2893 return nullptr;
2894}
2895
2896#if QT_CONFIG(accessibility)
2897/*!
2898 Sets the accessibleName of the tab at position \a index to \a name.
2899*/
2900void QTabBar::setAccessibleTabName(int index, const QString &name)
2901{
2902 Q_D(QTabBar);
2903 if (QTabBarPrivate::Tab *tab = d->at(index)) {
2904 tab->accessibleName = name;
2905 QAccessibleEvent event(this, QAccessible::NameChanged);
2906 event.setChild(index);
2907 QAccessible::updateAccessibility(&event);
2908 }
2909}
2910
2911/*!
2912 Returns the accessibleName of the tab at position \a index, or an empty
2913 string if \a index is out of range.
2914*/
2915QString QTabBar::accessibleTabName(int index) const
2916{
2917 Q_D(const QTabBar);
2918 if (const QTabBarPrivate::Tab *tab = d->at(index))
2919 return tab->accessibleName;
2920 return QString();
2921}
2922#endif // QT_CONFIG(accessibility)
2923
2924CloseButton::CloseButton(QWidget *parent)
2925 : QAbstractButton(parent)
2926{
2927 setFocusPolicy(Qt::NoFocus);
2928#ifndef QT_NO_CURSOR
2929 setCursor(Qt::ArrowCursor);
2930#endif
2931#if QT_CONFIG(tooltip)
2932 setToolTip(tr("Close Tab"));
2933#endif
2934 resize(sizeHint());
2935}
2936
2937QSize CloseButton::sizeHint() const
2938{
2939 ensurePolished();
2940 int width = style()->pixelMetric(QStyle::PM_TabCloseIndicatorWidth, nullptr, this);
2941 int height = style()->pixelMetric(QStyle::PM_TabCloseIndicatorHeight, nullptr, this);
2942 return QSize(width, height);
2943}
2944
2945void CloseButton::enterEvent(QEnterEvent *event)
2946{
2947 if (isEnabled())
2948 update();
2949 QAbstractButton::enterEvent(event);
2950}
2951
2952void CloseButton::leaveEvent(QEvent *event)
2953{
2954 if (isEnabled())
2955 update();
2956 QAbstractButton::leaveEvent(event);
2957}
2958
2959void CloseButton::paintEvent(QPaintEvent *)
2960{
2961 QPainter p(this);
2962 QStyleOption opt;
2963 opt.initFrom(this);
2964 opt.state |= QStyle::State_AutoRaise;
2965 if (isEnabled() && underMouse() && !isChecked() && !isDown())
2966 opt.state |= QStyle::State_Raised;
2967 if (isChecked())
2968 opt.state |= QStyle::State_On;
2969 if (isDown())
2970 opt.state |= QStyle::State_Sunken;
2971
2972 if (const QTabBar *tb = qobject_cast<const QTabBar *>(parent())) {
2973 int index = tb->currentIndex();
2974 QTabBar::ButtonPosition position = (QTabBar::ButtonPosition)style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, nullptr, tb);
2975 if (tb->tabButton(index, position) == this)
2976 opt.state |= QStyle::State_Selected;
2977 }
2978
2979 if (m_parentClipRect.isValid()) {
2980 auto tl = mapFromParent(m_parentClipRect.topLeft());
2981 auto br = mapFromParent(m_parentClipRect.bottomRight());
2982 p.setClipRect(QRect(tl, br));
2983 }
2984 style()->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, &p, this);
2985}
2986
2987#if QT_CONFIG(animation)
2988void QTabBarPrivate::Tab::TabBarAnimation::updateCurrentValue(const QVariant &current)
2989{
2990 priv->moveTab(priv->tabList.indexOf(tab), current.toInt());
2991}
2992
2993void QTabBarPrivate::Tab::TabBarAnimation::updateState(QAbstractAnimation::State newState, QAbstractAnimation::State)
2994{
2995 if (newState == Stopped) priv->moveTabFinished(priv->tabList.indexOf(tab));
2996}
2997#endif
2998
2999QT_END_NAMESPACE
3000
3001#include "moc_qtabbar.cpp"
3002#include "qtabbar.moc"
friend class QWidget
Definition qpainter.h:432
Combined button and popup list for selecting options.
static QString computeElidedText(Qt::TextElideMode mode, const QString &text)
Definition qtabbar.cpp:1553