Qt Utilities  5.12.2
Common Qt related C++ classes and routines used by my applications such as dialogs, widgets and models
iconbutton.cpp
Go to the documentation of this file.
1 #include "./iconbutton.h"
2 
3 #include <QKeyEvent>
4 #include <QStyle>
5 #include <QStyleOptionFocusRect>
6 #include <QStylePainter>
7 
8 namespace Widgets {
9 
18 IconButton::IconButton(QWidget *parent)
19  : QAbstractButton(parent)
20 {
21  setCursor(Qt::ArrowCursor);
22  setFocusPolicy(Qt::NoFocus);
23 }
24 
29 {
30 }
31 
32 QSize IconButton::sizeHint() const
33 {
34 #if QT_VERSION >= 0x050100
35  const qreal pixmapRatio = m_pixmap.devicePixelRatio();
36 #else
37  const qreal pixmapRatio = 1.0;
38 #endif
39  return QSize(m_pixmap.width() / pixmapRatio, m_pixmap.height() / pixmapRatio);
40 }
41 
42 void IconButton::paintEvent(QPaintEvent *)
43 {
44 #if QT_VERSION >= 0x050100
45  const qreal pixmapRatio = m_pixmap.devicePixelRatio();
46 #else
47  const qreal pixmapRatio = 1.0;
48 #endif
49  QStylePainter painter(this);
50  QRect pixmapRect = QRect(0, 0, m_pixmap.width() / pixmapRatio, m_pixmap.height() / pixmapRatio);
51  pixmapRect.moveCenter(rect().center());
52  painter.drawPixmap(pixmapRect, m_pixmap);
53  if (hasFocus()) {
54  QStyleOptionFocusRect focusOption;
55  focusOption.initFrom(this);
56  focusOption.rect = pixmapRect;
57 #ifdef Q_OS_MAC
58  focusOption.rect.adjust(-4, -4, 4, 4);
59  painter.drawControl(QStyle::CE_FocusFrame, focusOption);
60 #else
61  painter.drawPrimitive(QStyle::PE_FrameFocusRect, focusOption);
62 #endif
63  }
64 }
65 
66 void IconButton::keyPressEvent(QKeyEvent *event)
67 {
68  QAbstractButton::keyPressEvent(event);
69  if (!event->modifiers() && (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)) {
70  click();
71  }
72  event->accept();
73 }
74 
75 void IconButton::keyReleaseEvent(QKeyEvent *event)
76 {
77  QAbstractButton::keyReleaseEvent(event);
78  event->accept();
79 }
80 } // namespace Widgets
void paintEvent(QPaintEvent *event) override
Definition: iconbutton.cpp:42
void keyReleaseEvent(QKeyEvent *event) override
Definition: iconbutton.cpp:75
QSize sizeHint() const override
Definition: iconbutton.cpp:32
~IconButton() override
Destroys the icon button.
Definition: iconbutton.cpp:28
void keyPressEvent(QKeyEvent *event) override
Definition: iconbutton.cpp:66
Provides a set of extended widgets such as ClearLineEdit and ClearComboBox.
Definition: buttonoverlay.h:13
IconButton(QWidget *parent=nullptr)
Constructs an icon button.
Definition: iconbutton.cpp:18