Qt Utilities  5.10.0
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 <QStyleOptionFocusRect>
5 #include <QStylePainter>
6 
7 namespace Widgets {
8 
17 IconButton::IconButton(QWidget *parent)
18  : QAbstractButton(parent)
19 {
20  setCursor(Qt::ArrowCursor);
21  setFocusPolicy(Qt::NoFocus);
22 }
23 
28 {
29 }
30 
31 QSize IconButton::sizeHint() const
32 {
33 #if QT_VERSION >= 0x050100
34  const qreal pixmapRatio = m_pixmap.devicePixelRatio();
35 #else
36  const qreal pixmapRatio = 1.0;
37 #endif
38  return QSize(m_pixmap.width() / pixmapRatio, m_pixmap.height() / pixmapRatio);
39 }
40 
41 void IconButton::paintEvent(QPaintEvent *)
42 {
43 #if QT_VERSION >= 0x050100
44  const qreal pixmapRatio = m_pixmap.devicePixelRatio();
45 #else
46  const qreal pixmapRatio = 1.0;
47 #endif
48  QStylePainter painter(this);
49  QRect pixmapRect = QRect(0, 0, m_pixmap.width() / pixmapRatio, m_pixmap.height() / pixmapRatio);
50  pixmapRect.moveCenter(rect().center());
51  painter.drawPixmap(pixmapRect, m_pixmap);
52  if (hasFocus()) {
53  QStyleOptionFocusRect focusOption;
54  focusOption.initFrom(this);
55  focusOption.rect = pixmapRect;
56 #ifdef Q_OS_MAC
57  focusOption.rect.adjust(-4, -4, 4, 4);
58  painter.drawControl(QStyle::CE_FocusFrame, focusOption);
59 #else
60  painter.drawPrimitive(QStyle::PE_FrameFocusRect, focusOption);
61 #endif
62  }
63 }
64 
65 void IconButton::keyPressEvent(QKeyEvent *event)
66 {
67  QAbstractButton::keyPressEvent(event);
68  if (!event->modifiers() && (event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return)) {
69  click();
70  }
71  event->accept();
72 }
73 
74 void IconButton::keyReleaseEvent(QKeyEvent *event)
75 {
76  QAbstractButton::keyReleaseEvent(event);
77  event->accept();
78 }
79 } // namespace Widgets
QSize sizeHint() const
Definition: iconbutton.cpp:31
void keyReleaseEvent(QKeyEvent *event)
Definition: iconbutton.cpp:74
~IconButton()
Destroys the icon button.
Definition: iconbutton.cpp:27
void keyPressEvent(QKeyEvent *event)
Definition: iconbutton.cpp:65
void paintEvent(QPaintEvent *event)
Definition: iconbutton.cpp:41
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:17