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