CentralizedCheckBoxDelegate.cpp
Go to the documentation of this file.
2 
3 #include <QApplication>
4 #include <QMouseEvent>
5 
7 QStyledItemDelegate(parent)
8 {
9 }
10 
12  default;
13 
14 void te::qt::widgets::CentralizedCheckBoxDelegate::paint (QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
15 {
16  QStyleOptionViewItem viewItemOption(option);
17 
18  if (index.column() == 0)
19  {
20  const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;
21  QRect newRect = QStyle::alignedRect(option.direction, Qt::AlignCenter,
22  QSize(option.decorationSize.width() + 5,option.decorationSize.height()),
23  QRect(option.rect.x() + textMargin, option.rect.y(),
24  option.rect.width() - (2 * textMargin), option.rect.height()));
25  viewItemOption.rect = newRect;
26  }
27 
28  QStyledItemDelegate::paint(painter, viewItemOption, index);
29 }
30 
31 bool te::qt::widgets::CentralizedCheckBoxDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
32 {
33  Q_ASSERT(event);
34  Q_ASSERT(model);
35  Qt::ItemFlags flags = model->flags(index);
36  if (!(flags & Qt::ItemIsUserCheckable) || !(flags & Qt::ItemIsEnabled))
37  return false;
38 
39  QVariant value = index.data(Qt::CheckStateRole);
40  if (!value.isValid())
41  return false;
42 
43  // make sure that we have the right event type
44  if (event->type() == QEvent::MouseButtonRelease)
45  {
46  const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;
47  QRect checkRect = QStyle::alignedRect(option.direction, Qt::AlignCenter,
48  option.decorationSize,
49  QRect(option.rect.x() + (2 * textMargin), option.rect.y(),
50  option.rect.width() - (2 * textMargin),
51  option.rect.height()));
52 
53  if (!checkRect.contains(static_cast<QMouseEvent*>(event)->pos()))
54  return false;
55  }
56  else if (event->type() == QEvent::KeyPress)
57  {
58  if (static_cast<QKeyEvent*>(event)->key() != Qt::Key_Space&& static_cast<QKeyEvent*>(event)->key() != Qt::Key_Select)
59  return false;
60  }
61  else
62  {
63  return false;
64  }
65 
66  Qt::CheckState state = (static_cast<Qt::CheckState>(value.toInt()) == Qt::Checked ? Qt::Unchecked : Qt::Checked);
67 
68  return model->setData(index, state, Qt::CheckStateRole);
69 }
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
Just use a delegate to render checkboxes centralized on a view.
bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
void paint(te::qt::widgets::Canvas *c, bool generatePNG, std::string fileName)