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
qabstractbutton.cpp
Go to the documentation of this file.
1// Copyright (C) 2020 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/qabstractbutton_p.h"
6
7#if QT_CONFIG(itemviews)
8#include "qabstractitemview.h"
9#endif
10#if QT_CONFIG(buttongroup)
11#include "qbuttongroup.h"
12#include "private/qbuttongroup_p.h"
13#endif
14#include "private/qapplication_p.h"
16#include "qevent.h"
17#include "qpainter.h"
18#include "qapplication.h"
19#include "qstyle.h"
20#if QT_CONFIG(accessibility)
21#include "qaccessible.h"
22#endif
23#include <qpa/qplatformtheme.h>
24
25#include <QtCore/qpointer.h>
26
27#include <algorithm>
28
29using namespace std::chrono_literals;
30
32
33static constexpr auto AUTO_REPEAT_DELAY = 300ms;
34static constexpr auto AUTO_REPEAT_INTERVAL = 100ms;
35
36Q_WIDGETS_EXPORT extern bool qt_tab_all_widgets();
37
38/*!
39 \class QAbstractButton
40
41 \brief The QAbstractButton class is the abstract base class of
42 button widgets, providing functionality common to buttons.
43
44 \ingroup abstractwidgets
45 \inmodule QtWidgets
46
47 This class implements an \e abstract button.
48 Subclasses of this class handle user actions, and specify how the button
49 is drawn.
50
51 QAbstractButton provides support for both push buttons and checkable
52 (toggle) buttons. Checkable buttons are implemented in the QRadioButton
53 and QCheckBox classes. Push buttons are implemented in the
54 QPushButton and QToolButton classes; these also provide toggle
55 behavior if required.
56
57 Any button can display a label containing text and an icon. setText()
58 sets the text; setIcon() sets the icon. If a button is disabled, its label
59 is changed to give the button a "disabled" appearance.
60
61 If the button is a text button with a string containing an
62 ampersand ('&'), QAbstractButton automatically creates a shortcut
63 key. For example:
64
65 \snippet code/src_gui_widgets_qabstractbutton.cpp 0
66
67 The \uicontrol Alt+C shortcut is assigned to the button, i.e., when the
68 user presses \uicontrol Alt+C the button will call animateClick(). See
69 the \l {QShortcut#mnemonic}{QShortcut} documentation for details. To
70 display an actual ampersand, use '&&'.
71
72 You can also set a custom shortcut key using the setShortcut()
73 function. This is useful mostly for buttons that do not have any
74 text, and therefore can't have any automatic shortcut.
75
76 \snippet code/src_gui_widgets_qabstractbutton.cpp 1
77
78 All the buttons provided by Qt (QPushButton, QToolButton,
79 QCheckBox, and QRadioButton) can display both \l text and \l{icon}{icons}.
80
81 A button can be made the default button in a dialog by means of
82 QPushButton::setDefault() and QPushButton::setAutoDefault().
83
84 QAbstractButton provides most of the states used for buttons:
85
86 \list
87
88 \li isDown() indicates whether the button is \e pressed down.
89
90 \li isChecked() indicates whether the button is \e checked. Only
91 checkable buttons can be checked and unchecked (see below).
92
93 \li isEnabled() indicates whether the button can be pressed by the
94 user. \note As opposed to other widgets, buttons derived from
95 QAbstractButton accept mouse and context menu events
96 when disabled.
97
98 \li setAutoRepeat() sets whether the button will auto-repeat if the
99 user holds it down. \l autoRepeatDelay and \l autoRepeatInterval
100 define how auto-repetition is done.
101
102 \li setCheckable() sets whether the button is a toggle button or not.
103
104 \endlist
105
106 The difference between isDown() and isChecked() is as follows.
107 When the user clicks a toggle button to check it, the button is first
108 \e pressed then released into the \e checked state. When the user
109 clicks it again (to uncheck it), the button moves first to the
110 \e pressed state, then to the \e unchecked state (isChecked() and
111 isDown() are both false).
112
113 QAbstractButton provides four signals:
114
115 \list 1
116
117 \li pressed() is emitted when the left mouse button is pressed while
118 the mouse cursor is inside the button.
119
120 \li released() is emitted when the left mouse button is released.
121
122 \li clicked() is emitted when the button is first pressed and then
123 released, when the shortcut key is typed, or when click() or
124 animateClick() is called.
125
126 \li toggled() is emitted when the state of a toggle button changes.
127
128 \endlist
129
130 To subclass QAbstractButton, you must reimplement at least
131 paintEvent() to draw the button's outline and its text or pixmap. It
132 is generally advisable to reimplement sizeHint() as well, and
133 sometimes hitButton() (to determine whether a button press is within
134 the button). For buttons with more than two states (like tri-state
135 buttons), you will also have to reimplement checkStateSet() and
136 nextCheckState().
137
138 \sa QButtonGroup
139*/
140
141QAbstractButtonPrivate::QAbstractButtonPrivate(QSizePolicy::ControlType type)
142 :
143#ifndef QT_NO_SHORTCUT
144 shortcutId(0),
145#endif
146 checkable(false), checked(false), autoRepeat(false), autoExclusive(false),
147 down(false), blockRefresh(false), pressed(false),
148#if QT_CONFIG(buttongroup)
149 group(nullptr),
150#endif
151 autoRepeatDelay(AUTO_REPEAT_DELAY),
152 autoRepeatInterval(AUTO_REPEAT_INTERVAL),
153 controlType(type)
154{}
155
156QList<QAbstractButton *>QAbstractButtonPrivate::queryButtonList() const
157{
158#if QT_CONFIG(buttongroup)
159 if (group)
160 return group->d_func()->buttonList;
161#endif
162
163 if (!parent)
164 return {};
165 QList<QAbstractButton *> candidates = parent->findChildren<QAbstractButton *>();
166 if (autoExclusive) {
167 auto isNoMemberOfMyAutoExclusiveGroup = [](QAbstractButton *candidate) {
168 return !candidate->autoExclusive()
169#if QT_CONFIG(buttongroup)
170 || candidate->group()
171#endif
172 ;
173 };
174 candidates.removeIf(isNoMemberOfMyAutoExclusiveGroup);
175 }
176 return candidates;
177}
178
179QAbstractButton *QAbstractButtonPrivate::queryCheckedButton() const
180{
181#if QT_CONFIG(buttongroup)
182 if (group)
183 return group->d_func()->checkedButton;
184#endif
185
186 Q_Q(const QAbstractButton);
187 const QList<QAbstractButton *> buttonList = queryButtonList();
188 if (!autoExclusive || buttonList.size() == 1) // no group
189 return nullptr;
190
191 for (QAbstractButton *b : buttonList) {
192 if (b->d_func()->checked && b != q)
193 return b;
194 }
195 return checked ? const_cast<QAbstractButton *>(q) : nullptr;
196}
197
198void QAbstractButtonPrivate::notifyChecked()
199{
200#if QT_CONFIG(buttongroup)
201 Q_Q(QAbstractButton);
202 if (group) {
203 QAbstractButton *previous = group->d_func()->checkedButton;
204 group->d_func()->checkedButton = q;
205 if (group->d_func()->exclusive && previous && previous != q)
206 previous->nextCheckState();
207 } else
208#endif
209 if (autoExclusive) {
210 if (QAbstractButton *b = queryCheckedButton())
211 b->setChecked(false);
212 }
213}
214
215void QAbstractButtonPrivate::moveFocus(int key)
216{
217 const QList<QAbstractButton *> buttonList = queryButtonList();
218#if QT_CONFIG(buttongroup)
219 bool exclusive = group ? group->d_func()->exclusive : autoExclusive;
220#else
221 bool exclusive = autoExclusive;
222#endif
223 QWidget *f = QApplication::focusWidget();
224 QAbstractButton *fb = qobject_cast<QAbstractButton *>(f);
225 if (!fb || !buttonList.contains(fb))
226 return;
227
228 QAbstractButton *candidate = nullptr;
229 int bestScore = -1;
230 QRect target = f->rect().translated(f->mapToGlobal(QPoint(0,0)));
231 QPoint goal = target.center();
232 uint focus_flag = qt_tab_all_widgets() ? Qt::TabFocus : Qt::StrongFocus;
233
234 for (QAbstractButton *button : buttonList) {
235 if (button != f && button->window() == f->window() && button->isEnabled() && !button->isHidden() &&
236 (exclusive || (button->focusPolicy() & focus_flag) == focus_flag)) {
237 QRect buttonRect = button->rect().translated(button->mapToGlobal(QPoint(0,0)));
238 QPoint p = buttonRect.center();
239
240 //Priority to widgets that overlap on the same coordinate.
241 //In that case, the distance in the direction will be used as significant score,
242 //take also in account orthogonal distance in case two widget are in the same distance.
243 int score;
244 if ((buttonRect.x() < target.right() && target.x() < buttonRect.right())
245 && (key == Qt::Key_Up || key == Qt::Key_Down)) {
246 //one item's is at the vertical of the other
247 score = (qAbs(p.y() - goal.y()) << 16) + qAbs(p.x() - goal.x());
248 } else if ((buttonRect.y() < target.bottom() && target.y() < buttonRect.bottom())
249 && (key == Qt::Key_Left || key == Qt::Key_Right) ) {
250 //one item's is at the horizontal of the other
251 score = (qAbs(p.x() - goal.x()) << 16) + qAbs(p.y() - goal.y());
252 } else {
253 score = (1 << 30) + (p.y() - goal.y()) * (p.y() - goal.y()) + (p.x() - goal.x()) * (p.x() - goal.x());
254 }
255
256 if (score > bestScore && candidate)
257 continue;
258
259 switch(key) {
260 case Qt::Key_Up:
261 if (p.y() < goal.y()) {
262 candidate = button;
263 bestScore = score;
264 }
265 break;
266 case Qt::Key_Down:
267 if (p.y() > goal.y()) {
268 candidate = button;
269 bestScore = score;
270 }
271 break;
272 case Qt::Key_Left:
273 if (p.x() < goal.x()) {
274 candidate = button;
275 bestScore = score;
276 }
277 break;
278 case Qt::Key_Right:
279 if (p.x() > goal.x()) {
280 candidate = button;
281 bestScore = score;
282 }
283 break;
284 }
285 }
286 }
287
288 if (exclusive
289 && candidate
290 && fb->d_func()->checked
291 && candidate->d_func()->checkable)
292 candidate->click();
293
294 if (candidate) {
295 if (key == Qt::Key_Up || key == Qt::Key_Left)
296 candidate->setFocus(Qt::BacktabFocusReason);
297 else
298 candidate->setFocus(Qt::TabFocusReason);
299 }
300}
301
302void QAbstractButtonPrivate::fixFocusPolicy()
303{
304 Q_Q(QAbstractButton);
305#if QT_CONFIG(buttongroup)
306 const bool exclusive = group ? group->d_func()->exclusive : autoExclusive;
307#else
308 const bool exclusive = autoExclusive;
309#endif
310 if (!exclusive)
311 return;
312
313 const QList<QAbstractButton *> buttonList = queryButtonList();
314 for (QAbstractButton *b : buttonList) {
315 if (!b->isCheckable())
316 continue;
317 b->setFocusPolicy((Qt::FocusPolicy) ((b == q || !q->isCheckable())
318 ? (b->focusPolicy() | Qt::TabFocus)
319 : (b->focusPolicy() & ~Qt::TabFocus)));
320 }
321}
322
323void QAbstractButtonPrivate::init()
324{
325 Q_Q(QAbstractButton);
326
327 // Query focus policy. Don't pass the QWidget pointer since QStyleSheetStyle will
328 // (if in use) cache it derive incorrect style metrics from it.
329 q->setFocusPolicy(Qt::FocusPolicy(q->style()->styleHint(QStyle::SH_Button_FocusPolicy,
330 nullptr, nullptr)));
331 q->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed, controlType));
332 q->setAttribute(Qt::WA_WState_OwnSizePolicy, false);
333 q->setForegroundRole(QPalette::ButtonText);
334 q->setBackgroundRole(QPalette::Button);
335}
336
337void QAbstractButtonPrivate::refresh()
338{
339 Q_Q(QAbstractButton);
340
341 if (blockRefresh)
342 return;
343 q->update();
344}
345
346void QAbstractButtonPrivate::click()
347{
348 Q_Q(QAbstractButton);
349
350 down = false;
351 blockRefresh = true;
352 bool changeState = true;
353 if (checked && queryCheckedButton() == q) {
354 // the checked button of an exclusive or autoexclusive group cannot be unchecked
355#if QT_CONFIG(buttongroup)
356 if (group ? group->d_func()->exclusive : autoExclusive)
357#else
358 if (autoExclusive)
359#endif
360 changeState = false;
361 }
362
363 QPointer<QAbstractButton> guard(q);
364 if (changeState) {
365 q->nextCheckState();
366 if (!guard)
367 return;
368 }
369 blockRefresh = false;
370 refresh();
371 q->repaint();
372 if (guard)
373 emitReleased();
374 if (guard)
375 emitClicked();
376}
377
378void QAbstractButtonPrivate::emitClicked()
379{
380 Q_Q(QAbstractButton);
381 QPointer<QAbstractButton> guard(q);
382 emit q->clicked(checked);
383#if QT_CONFIG(buttongroup)
384 if (guard && group) {
385 emit group->idClicked(group->id(q));
386 if (guard && group)
387 emit group->buttonClicked(q);
388 }
389#endif
390}
391
392void QAbstractButtonPrivate::emitPressed()
393{
394 Q_Q(QAbstractButton);
395 QPointer<QAbstractButton> guard(q);
396 emit q->pressed();
397#if QT_CONFIG(buttongroup)
398 if (guard && group) {
399 emit group->idPressed(group->id(q));
400 if (guard && group)
401 emit group->buttonPressed(q);
402 }
403#endif
404}
405
406void QAbstractButtonPrivate::emitReleased()
407{
408 Q_Q(QAbstractButton);
409 QPointer<QAbstractButton> guard(q);
410 emit q->released();
411#if QT_CONFIG(buttongroup)
412 if (guard && group) {
413 emit group->idReleased(group->id(q));
414 if (guard && group)
415 emit group->buttonReleased(q);
416 }
417#endif
418}
419
420void QAbstractButtonPrivate::emitToggled(bool checked)
421{
422 Q_Q(QAbstractButton);
423 QPointer<QAbstractButton> guard(q);
424 emit q->toggled(checked);
425#if QT_CONFIG(buttongroup)
426 if (guard && group) {
427 emit group->idToggled(group->id(q), checked);
428 if (guard && group)
429 emit group->buttonToggled(q, checked);
430 }
431#endif
432}
433
434QStyle::State QAbstractButtonPrivate::styleButtonState(QStyle::State state) const
435{
436 if (down)
437 state |= QStyle::State_Sunken;
438 return state;
439}
440
441/*!
442 Constructs an abstract button with a \a parent.
443*/
444QAbstractButton::QAbstractButton(QWidget *parent)
445 : QWidget(*new QAbstractButtonPrivate, parent, { })
446{
447 Q_D(QAbstractButton);
448 d->init();
449}
450
451/*!
452 Destroys the button.
453 */
454 QAbstractButton::~QAbstractButton()
455{
456#if QT_CONFIG(buttongroup)
457 Q_D(QAbstractButton);
458 if (d->group)
459 d->group->removeButton(this);
460#endif
461}
462
463
464/*! \internal
465 */
466QAbstractButton::QAbstractButton(QAbstractButtonPrivate &dd, QWidget *parent)
467 : QWidget(dd, parent, { })
468{
469 Q_D(QAbstractButton);
470 d->init();
471}
472
473/*!
474\property QAbstractButton::text
475\brief the text shown on the button
476
477If the button has no text, the text() function will return an empty
478string.
479
480If the text contains an ampersand character ('&'), a shortcut is
481automatically created for it. The character that follows the '&' will
482be used as the shortcut key. Any previous shortcut will be
483overwritten or cleared if no shortcut is defined by the text. See the
484\l {QShortcut#mnemonic}{QShortcut} documentation for details. To
485display an actual ampersand, use '&&'.
486
487There is no default text.
488*/
489
490void QAbstractButton::setText(const QString &text)
491{
492 Q_D(QAbstractButton);
493 if (d->text == text)
494 return;
495 d->text = text;
496#ifndef QT_NO_SHORTCUT
497 QKeySequence newMnemonic = QKeySequence::mnemonic(text);
498 setShortcut(newMnemonic);
499#endif
500 d->sizeHint = QSize();
501 update();
502 updateGeometry();
503#if QT_CONFIG(accessibility)
504 QAccessibleEvent event(this, QAccessible::NameChanged);
505 QAccessible::updateAccessibility(&event);
506#endif
507}
508
509QString QAbstractButton::text() const
510{
511 Q_D(const QAbstractButton);
512 return d->text;
513}
514
515
516/*!
517 \property QAbstractButton::icon
518 \brief the icon shown on the button
519
520 The icon's default size is defined by the GUI style, but can be
521 adjusted by setting the \l iconSize property.
522*/
523void QAbstractButton::setIcon(const QIcon &icon)
524{
525 Q_D(QAbstractButton);
526 d->icon = icon;
527 d->sizeHint = QSize();
528 update();
529 updateGeometry();
530}
531
532QIcon QAbstractButton::icon() const
533{
534 Q_D(const QAbstractButton);
535 return d->icon;
536}
537
538#ifndef QT_NO_SHORTCUT
539/*!
540\property QAbstractButton::shortcut
541\brief the mnemonic associated with the button
542*/
543
544void QAbstractButton::setShortcut(const QKeySequence &key)
545{
546 Q_D(QAbstractButton);
547 if (d->shortcutId != 0)
548 releaseShortcut(d->shortcutId);
549 d->shortcut = key;
550 d->shortcutId = grabShortcut(key);
551}
552
553QKeySequence QAbstractButton::shortcut() const
554{
555 Q_D(const QAbstractButton);
556 return d->shortcut;
557}
558#endif // QT_NO_SHORTCUT
559
560/*!
561\property QAbstractButton::checkable
562\brief whether the button is checkable
563
564By default, the button is not checkable.
565
566\sa checked
567*/
568void QAbstractButton::setCheckable(bool checkable)
569{
570 Q_D(QAbstractButton);
571 if (d->checkable == checkable)
572 return;
573
574 d->checkable = checkable;
575 d->checked = false;
576}
577
578bool QAbstractButton::isCheckable() const
579{
580 Q_D(const QAbstractButton);
581 return d->checkable;
582}
583
584/*!
585\property QAbstractButton::checked
586\brief whether the button is checked
587
588Only checkable buttons can be checked. By default, the button is unchecked.
589
590\sa checkable
591*/
592void QAbstractButton::setChecked(bool checked)
593{
594 Q_D(QAbstractButton);
595 if (!d->checkable || d->checked == checked) {
596 if (!d->blockRefresh)
597 checkStateSet();
598 return;
599 }
600
601 if (!checked && d->queryCheckedButton() == this) {
602 // the checked button of an exclusive or autoexclusive group cannot be unchecked
603#if QT_CONFIG(buttongroup)
604 if (d->group ? d->group->d_func()->exclusive : d->autoExclusive)
605 return;
606 if (d->group)
607 d->group->d_func()->detectCheckedButton();
608#else
609 if (d->autoExclusive)
610 return;
611#endif
612 }
613
614 QPointer<QAbstractButton> guard(this);
615
616 d->checked = checked;
617 if (!d->blockRefresh)
618 checkStateSet();
619 d->refresh();
620
621 if (guard && checked)
622 d->notifyChecked();
623 if (guard)
624 d->emitToggled(checked);
625
626#if QT_CONFIG(accessibility)
627 if (guard) {
628 QAccessible::State s;
629 s.checked = true;
630 QAccessibleStateChangeEvent event(this, s);
631 QAccessible::updateAccessibility(&event);
632 }
633#endif
634}
635
636bool QAbstractButton::isChecked() const
637{
638 Q_D(const QAbstractButton);
639 return d->checked;
640}
641
642/*!
643 \property QAbstractButton::down
644 \brief whether the button is pressed down
645
646 If this property is \c true, the button is pressed down. The signals
647 pressed() and clicked() are not emitted if you set this property
648 to true. The default is false.
649*/
650
651void QAbstractButton::setDown(bool down)
652{
653 Q_D(QAbstractButton);
654 if (d->down == down)
655 return;
656 d->down = down;
657 d->refresh();
658 if (d->autoRepeat && d->down)
659 d->repeatTimer.start(d->autoRepeatDelay, this);
660 else
661 d->repeatTimer.stop();
662}
663
664bool QAbstractButton::isDown() const
665{
666 Q_D(const QAbstractButton);
667 return d->down;
668}
669
670/*!
671\property QAbstractButton::autoRepeat
672\brief whether autoRepeat is enabled
673
674If autoRepeat is enabled, then the pressed(), released(), and clicked() signals are emitted at
675regular intervals when the button is down. autoRepeat is off by default.
676The initial delay and the repetition interval are defined in milliseconds by \l
677autoRepeatDelay and \l autoRepeatInterval.
678
679Note: If a button is pressed down by a shortcut key, then auto-repeat is enabled and timed by the
680system and not by this class. The pressed(), released(), and clicked() signals will be emitted
681like in the normal case.
682*/
683
684void QAbstractButton::setAutoRepeat(bool autoRepeat)
685{
686 Q_D(QAbstractButton);
687 if (d->autoRepeat == autoRepeat)
688 return;
689 d->autoRepeat = autoRepeat;
690 if (d->autoRepeat && d->down)
691 d->repeatTimer.start(d->autoRepeatDelay, this);
692 else
693 d->repeatTimer.stop();
694}
695
696bool QAbstractButton::autoRepeat() const
697{
698 Q_D(const QAbstractButton);
699 return d->autoRepeat;
700}
701
702/*!
703 \property QAbstractButton::autoRepeatDelay
704 \brief the initial delay of auto-repetition
705 \since 4.2
706
707 If \l autoRepeat is enabled, then autoRepeatDelay defines the initial
708 delay in milliseconds before auto-repetition kicks in.
709
710 \sa autoRepeat, autoRepeatInterval
711*/
712void QAbstractButton::setAutoRepeatDelay(int autoRepeatDelay)
713{
714 setAutoRepeatDelay(std::chrono::milliseconds(autoRepeatDelay));
715}
716
717int QAbstractButton::autoRepeatDelay() const
718{
719 Q_D(const QAbstractButton);
720 return d->autoRepeatDelay.count();
721}
722/*!
723 \since 6.13
724 \overload
725
726 Sets the auto-repeat delay to \a autoRepeatDelay.
727
728 \sa autoRepeatDelayAsDuration()
729*/
730void QAbstractButton::setAutoRepeatDelay(std::chrono::milliseconds autoRepeatDelay)
731{
732 Q_D(QAbstractButton);
733 d->autoRepeatDelay = autoRepeatDelay;
734}
735
736
737/*!
738 Returns the auto-repetition delay as std::chrono::milliseconds
739
740 \since 6.13
741 \sa autoRepeatDelay
742*/
743std::chrono::milliseconds QAbstractButton::autoRepeatDelayAsDuration() const
744{
745 Q_D(const QAbstractButton);
746 return d->autoRepeatDelay;
747}
748
749/*!
750 \property QAbstractButton::autoRepeatInterval
751 \brief the interval of auto-repetition
752 \since 4.2
753
754 If \l autoRepeat is enabled, then autoRepeatInterval defines the
755 length of the auto-repetition interval in millisecons.
756
757 \sa autoRepeat, autoRepeatDelay
758*/
759
760void QAbstractButton::setAutoRepeatInterval(int autoRepeatInterval)
761{
762 setAutoRepeatInterval(std::chrono::milliseconds(autoRepeatInterval));
763}
764
765int QAbstractButton::autoRepeatInterval() const
766{
767 Q_D(const QAbstractButton);
768 return d->autoRepeatInterval.count();
769}
770
771/*!
772 \since 6.13
773 \overload
774
775 Sets the auto-repetition interval to \a autoRepeatInterval.
776
777 \sa autoRepeatDelayAsDuration()
778*/
779void QAbstractButton::setAutoRepeatInterval(std::chrono::milliseconds autoRepeatInterval)
780{
781 Q_D(QAbstractButton);
782 d->autoRepeatInterval = autoRepeatInterval;
783}
784
785
786/*!
787 Returns the auto-repetition interval as std::chrono::milliseconds
788
789 \since 6.13
790 \sa autoRepeatInterval
791*/
792std::chrono::milliseconds QAbstractButton::autoRepeatIntervalAsDuration() const
793{
794 Q_D(const QAbstractButton);
795 return d->autoRepeatInterval;
796}
797
798/*!
799\property QAbstractButton::autoExclusive
800\brief whether auto-exclusivity is enabled
801
802If auto-exclusivity is enabled, checkable buttons that belong to the
803same parent widget behave as if they were part of the same
804exclusive button group. In an exclusive button group, only one button
805can be checked at any time; checking another button automatically
806unchecks the previously checked one.
807
808The property has no effect on buttons that belong to a button
809group.
810
811autoExclusive is off by default, except for radio buttons.
812
813\sa QRadioButton
814*/
815void QAbstractButton::setAutoExclusive(bool autoExclusive)
816{
817 Q_D(QAbstractButton);
818 d->autoExclusive = autoExclusive;
819}
820
821bool QAbstractButton::autoExclusive() const
822{
823 Q_D(const QAbstractButton);
824 return d->autoExclusive;
825}
826
827#if QT_CONFIG(buttongroup)
828/*!
829 Returns the group that this button belongs to.
830
831 If the button is not a member of any QButtonGroup, this function
832 returns \nullptr.
833
834 \sa QButtonGroup
835*/
836QButtonGroup *QAbstractButton::group() const
837{
838 Q_D(const QAbstractButton);
839 return d->group;
840}
841#endif // QT_CONFIG(buttongroup)
842
843/*!
844Performs an animated click: the button is pressed immediately, and
845released 100ms later.
846
847Calling this function again before the button is released resets
848the release timer.
849
850All signals associated with a click are emitted as appropriate.
851
852This function does nothing if the button is \l{setEnabled()}{disabled.}
853
854\sa click()
855*/
856void QAbstractButton::animateClick()
857{
858 if (!isEnabled())
859 return;
860 Q_D(QAbstractButton);
861 if (d->checkable && focusPolicy() & Qt::ClickFocus)
862 setFocus();
863 setDown(true);
864 repaint();
865 if (!d->animateTimer.isActive())
866 d->emitPressed();
867 d->animateTimer.start(100, this);
868}
869
870/*!
871Performs a click.
872
873All the usual signals associated with a click are emitted as
874appropriate. If the button is checkable, the state of the button is
875toggled.
876
877This function does nothing if the button is \l{setEnabled()}{disabled.}
878
879\sa animateClick()
880 */
881void QAbstractButton::click()
882{
883 if (!isEnabled())
884 return;
885 Q_D(QAbstractButton);
886 QPointer<QAbstractButton> guard(this);
887 d->down = true;
888 d->emitPressed();
889 if (guard) {
890 d->down = false;
891 nextCheckState();
892 if (guard)
893 d->emitReleased();
894 if (guard)
895 d->emitClicked();
896 }
897}
898
899/*! \fn void QAbstractButton::toggle()
900
901 Toggles the state of a checkable button.
902
903 \sa checked
904*/
905void QAbstractButton::toggle()
906{
907 Q_D(QAbstractButton);
908 setChecked(!d->checked);
909}
910
911
912/*! This virtual handler is called when setChecked() is used,
913unless it is called from within nextCheckState(). It allows
914subclasses to reset their intermediate button states.
915
916\sa nextCheckState()
917 */
918void QAbstractButton::checkStateSet()
919{
920}
921
922/*! This virtual handler is called when a button is clicked. The
923default implementation calls setChecked(!isChecked()) if the button
924isCheckable(). It allows subclasses to implement intermediate button
925states.
926
927\sa checkStateSet()
928*/
929void QAbstractButton::nextCheckState()
930{
931 if (isCheckable())
932 setChecked(!isChecked());
933}
934
935/*!
936Returns \c true if \a pos is inside the clickable button rectangle;
937otherwise returns \c false.
938
939By default, the clickable area is the entire widget. Subclasses
940may reimplement this function to provide support for clickable
941areas of different shapes and sizes.
942*/
943bool QAbstractButton::hitButton(const QPoint &pos) const
944{
945 return rect().contains(pos);
946}
947
948/*! \reimp */
949bool QAbstractButton::event(QEvent *e)
950{
951 // as opposed to other widgets, disabled buttons accept mouse
952 // events. This avoids surprising click-through scenarios
953 if (!isEnabled()) {
954 switch(e->type()) {
955 case QEvent::TabletPress:
956 case QEvent::TabletRelease:
957 case QEvent::TabletMove:
958 case QEvent::MouseButtonPress:
959 case QEvent::MouseButtonRelease:
960 case QEvent::MouseButtonDblClick:
961 case QEvent::MouseMove:
962 case QEvent::HoverMove:
963 case QEvent::HoverEnter:
964 case QEvent::HoverLeave:
965 case QEvent::ContextMenu:
966 return true;
967 default:
968 break;
969 }
970 }
971
972#ifndef QT_NO_SHORTCUT
973 if (e->type() == QEvent::Shortcut) {
974 Q_D(QAbstractButton);
975 QShortcutEvent *se = static_cast<QShortcutEvent *>(e);
976 if (d->shortcutId != se->shortcutId())
977 return false;
978 if (!se->isAmbiguous()) {
979 if (!d->animateTimer.isActive())
980 animateClick();
981 } else {
982 if (focusPolicy() != Qt::NoFocus)
983 setFocus(Qt::ShortcutFocusReason);
984 window()->setAttribute(Qt::WA_KeyboardFocusChange);
985 }
986 return true;
987 }
988#endif
989 return QWidget::event(e);
990}
991
992/*! \reimp */
993void QAbstractButton::mousePressEvent(QMouseEvent *e)
994{
995 Q_D(QAbstractButton);
996 if (e->button() != Qt::LeftButton) {
997 e->ignore();
998 return;
999 }
1000 if (hitButton(e->position().toPoint())) {
1001 setDown(true);
1002 d->pressed = true;
1003 repaint();
1004 d->emitPressed();
1005 e->accept();
1006 } else {
1007 e->ignore();
1008 }
1009}
1010
1011/*! \reimp */
1012void QAbstractButton::mouseReleaseEvent(QMouseEvent *e)
1013{
1014 Q_D(QAbstractButton);
1015
1016 if (e->button() != Qt::LeftButton) {
1017 e->ignore();
1018 return;
1019 }
1020
1021 d->pressed = false;
1022
1023 if (!d->down) {
1024 // refresh is required by QMacStyle to resume the default button animation
1025 d->refresh();
1026 e->ignore();
1027 return;
1028 }
1029
1030 if (hitButton(e->position().toPoint())) {
1031 d->repeatTimer.stop();
1032 d->click();
1033 e->accept();
1034 } else {
1035 setDown(false);
1036 e->ignore();
1037 }
1038}
1039
1040/*! \reimp */
1041void QAbstractButton::mouseMoveEvent(QMouseEvent *e)
1042{
1043 Q_D(QAbstractButton);
1044 if (!(e->buttons() & Qt::LeftButton) || !d->pressed) {
1045 e->ignore();
1046 return;
1047 }
1048
1049 if (hitButton(e->position().toPoint()) != d->down) {
1050 setDown(!d->down);
1051 repaint();
1052 if (d->down)
1053 d->emitPressed();
1054 else
1055 d->emitReleased();
1056 e->accept();
1057 } else if (!hitButton(e->position().toPoint())) {
1058 e->ignore();
1059 }
1060}
1061
1062/*! \reimp */
1063void QAbstractButton::keyPressEvent(QKeyEvent *e)
1064{
1065 Q_D(QAbstractButton);
1066 bool next = true;
1067
1068 const auto key = e->key();
1069 const auto buttonPressKeys = QGuiApplicationPrivate::platformTheme()
1070 ->themeHint(QPlatformTheme::ButtonPressKeys)
1071 .value<QList<Qt::Key>>();
1072 if (buttonPressKeys.contains(key) && !e->isAutoRepeat()) {
1073 setDown(true);
1074 repaint();
1075 d->emitPressed();
1076 return;
1077 }
1078
1079 switch (key) {
1080 case Qt::Key_Up:
1081 next = false;
1082 Q_FALLTHROUGH();
1083 case Qt::Key_Left:
1084 case Qt::Key_Right:
1085 case Qt::Key_Down: {
1086 QWidget *pw = parentWidget();
1087 if (d->autoExclusive
1088#if QT_CONFIG(buttongroup)
1089 || d->group
1090#endif
1091#if QT_CONFIG(itemviews)
1092 || (pw && qobject_cast<QAbstractItemView *>(pw->parentWidget()))
1093#endif
1094 ) {
1095 // ### Using qobject_cast to check if the parent is a viewport of
1096 // QAbstractItemView is a crude hack, and should be revisited and
1097 // cleaned up when fixing task 194373. It's here to ensure that we
1098 // keep compatibility outside QAbstractItemView.
1099 d->moveFocus(e->key());
1100 if (hasFocus()) // nothing happened, propagate
1101 e->ignore();
1102 } else {
1103 // Prefer parent widget, use this if parent is absent
1104 QWidget *w = pw ? pw : this;
1105 bool reverse = (w->layoutDirection() == Qt::RightToLeft);
1106 if ((e->key() == Qt::Key_Left && !reverse)
1107 || (e->key() == Qt::Key_Right && reverse)) {
1108 next = false;
1109 }
1110 focusNextPrevChild(next);
1111 }
1112 break;
1113 }
1114 default:
1115#ifndef QT_NO_SHORTCUT
1116 if (e->matches(QKeySequence::Cancel) && d->down) {
1117 setDown(false);
1118 repaint();
1119 d->emitReleased();
1120 return;
1121 }
1122#endif
1123 e->ignore();
1124 }
1125}
1126
1127/*! \reimp */
1128void QAbstractButton::keyReleaseEvent(QKeyEvent *e)
1129{
1130 Q_D(QAbstractButton);
1131
1132 if (!e->isAutoRepeat())
1133 d->repeatTimer.stop();
1134
1135 const auto buttonPressKeys = QGuiApplicationPrivate::platformTheme()
1136 ->themeHint(QPlatformTheme::ButtonPressKeys)
1137 .value<QList<Qt::Key>>();
1138 if (buttonPressKeys.contains(e->key()) && !e->isAutoRepeat() && d->down) {
1139 d->click();
1140 return;
1141 }
1142
1143 e->ignore();
1144}
1145
1146/*!\reimp
1147 */
1148void QAbstractButton::timerEvent(QTimerEvent *e)
1149{
1150 Q_D(QAbstractButton);
1151 if (e->timerId() == d->repeatTimer.timerId()) {
1152 d->repeatTimer.start(d->autoRepeatInterval, this);
1153 if (d->down) {
1154 QPointer<QAbstractButton> guard(this);
1155 nextCheckState();
1156 if (guard)
1157 d->emitReleased();
1158 if (guard)
1159 d->emitClicked();
1160 if (guard)
1161 d->emitPressed();
1162 }
1163 } else if (e->timerId() == d->animateTimer.timerId()) {
1164 d->animateTimer.stop();
1165 d->click();
1166 }
1167}
1168
1169/*! \reimp */
1170void QAbstractButton::focusInEvent(QFocusEvent *e)
1171{
1172 Q_D(QAbstractButton);
1173 d->fixFocusPolicy();
1174 QWidget::focusInEvent(e);
1175}
1176
1177/*! \reimp */
1178void QAbstractButton::focusOutEvent(QFocusEvent *e)
1179{
1180 Q_D(QAbstractButton);
1181 if (e->reason() != Qt::PopupFocusReason && d->down) {
1182 d->down = false;
1183 d->emitReleased();
1184 }
1185 QWidget::focusOutEvent(e);
1186}
1187
1188/*! \reimp */
1189void QAbstractButton::changeEvent(QEvent *e)
1190{
1191 Q_D(QAbstractButton);
1192 switch (e->type()) {
1193 case QEvent::EnabledChange:
1194 if (!isEnabled() && d->down) {
1195 d->down = false;
1196 d->emitReleased();
1197 }
1198 break;
1199 default:
1200 d->sizeHint = QSize();
1201 break;
1202 }
1203 QWidget::changeEvent(e);
1204}
1205
1206/*!
1207 \fn void QAbstractButton::paintEvent(QPaintEvent *e)
1208 \reimp
1209*/
1210
1211/*!
1212 \fn void QAbstractButton::pressed()
1213
1214 This signal is emitted when the button is pressed down.
1215
1216 \sa released(), clicked()
1217*/
1218
1219/*!
1220 \fn void QAbstractButton::released()
1221
1222 This signal is emitted when the button is released.
1223
1224 \sa pressed(), clicked(), toggled()
1225*/
1226
1227/*!
1228\fn void QAbstractButton::clicked(bool checked)
1229
1230This signal is emitted when the button is activated (i.e., pressed down
1231then released while the mouse cursor is inside the button), when the
1232shortcut key is typed, or when click() or animateClick() is called.
1233Notably, this signal is \e not emitted if you call setDown(),
1234setChecked() or toggle().
1235
1236If the button is checkable, \a checked is true if the button is
1237checked, or false if the button is unchecked.
1238
1239\sa pressed(), released(), toggled()
1240*/
1241
1242/*!
1243\fn void QAbstractButton::toggled(bool checked)
1244
1245This signal is emitted whenever a checkable button changes its state.
1246\a checked is true if the button is checked, or false if the button is
1247unchecked.
1248
1249This may be the result of a user action, click() slot activation,
1250or because setChecked() is called.
1251
1252The states of buttons in exclusive button groups are updated before this
1253signal is emitted. This means that slots can act on either the "off"
1254signal or the "on" signal emitted by the buttons in the group whose
1255states have changed.
1256
1257For example, a slot that reacts to signals emitted by newly checked
1258buttons but which ignores signals from buttons that have been unchecked
1259can be implemented using the following pattern:
1260
1261\snippet code/src_gui_widgets_qabstractbutton.cpp 2
1262
1263Button groups can be created using the QButtonGroup class, and
1264updates to the button states monitored with the
1265\l{QButtonGroup::buttonClicked()} signal.
1266
1267\sa checked, clicked()
1268*/
1269
1270/*!
1271 \property QAbstractButton::iconSize
1272 \brief the icon size used for this button.
1273
1274 The default size is defined by the GUI style. This is a maximum
1275 size for the icons. Smaller icons will not be scaled up.
1276*/
1277
1278QSize QAbstractButton::iconSize() const
1279{
1280 Q_D(const QAbstractButton);
1281 if (d->iconSize.isValid())
1282 return d->iconSize;
1283 QStyleOption opt;
1284 opt.initFrom(this);
1285 opt.state = d->styleButtonState(opt.state);
1286 int e = style()->pixelMetric(QStyle::PM_ButtonIconSize, &opt, this);
1287 return QSize(e, e);
1288}
1289
1290void QAbstractButton::setIconSize(const QSize &size)
1291{
1292 Q_D(QAbstractButton);
1293 if (d->iconSize == size)
1294 return;
1295
1296 d->iconSize = size;
1297 d->sizeHint = QSize();
1298 updateGeometry();
1299 if (isVisible()) {
1300 update();
1301 }
1302}
1303
1304
1305
1306QT_END_NAMESPACE
1307
1308#include "moc_qabstractbutton.cpp"
friend class QWidget
Definition qpainter.h:432
static constexpr auto AUTO_REPEAT_INTERVAL
static QT_BEGIN_NAMESPACE constexpr auto AUTO_REPEAT_DELAY
Q_WIDGETS_EXPORT bool qt_tab_all_widgets()