1

I am working with simple QTreeView. Each row of tree is a specific class inherited from one class EditorRow.

EditorRow has these functions:

virtual QVariant data(ColumnIndexEnum index, int role = Qt::DisplayRole) const = 0;
virtual void setData(const QVariant& data, ColumnIndexEnum index, int role = Qt::UserRole);
virtual QWidget* getEditor(QWidget* parent) const;

Each row has its specific widget, which is shown in the right column when selecting that row. When the row is not selected data function returns appropriate value for each row(f.e. the value which was chosen in the QComboBox).

But in case of row, which's widget is QCheckBox, I need to draw a checked(or unchecked) checkbox when the row is not selected.

I have tried to use Decoration role like this:

if(Qt::DecorationRole == role)
  {
    if(ValueColumn == index)
    {
      QStyle* style = QApplication::style();
      QStyleOptionButton opt;
      opt.state |= QStyle::State_Enabled;

      if(isChecked())
         opt.state = QStyle::State_On;
      else
         opt.state = QStyle::State_Off;


      const int indicatorWidth = style->pixelMetric(QStyle::PM_IndicatorWidth, &opt);
      const int indicatorHeight = style->pixelMetric(QStyle::PM_IndicatorHeight, &opt);
      const int listViewIconSize = indicatorWidth;
      const int pixmapWidth = indicatorWidth;
      const int pixmapHeight = qMax(indicatorHeight, listViewIconSize);

      opt.rect = QRect(0, 0, indicatorWidth, indicatorHeight);

      QPixmap pixmap = QPixmap(pixmapWidth, pixmapHeight);
      pixmap.fill(Qt::transparent);
      {
      QPainter painter(&pixmap);
      QCheckBox cb;
      cb.setLayoutDirection(Qt::RightToLeft);
      style->drawPrimitive(QStyle::PE_IndicatorCheckBox, &opt, &painter, &cb);
      }
      return QIcon(pixmap);
    }
}

It actually works, but the icon is shown always, even when the row is selected. I think it is because of DecorationRole.

Do You have any ideas how to handle this problem ?

Thank You.

Karen Tsirunyan
  • 1,938
  • 6
  • 19
  • 30
  • 3
    Why don't you use `Qt::ItemIsUserCheckable` flag for your chackable items? It will automatically draw the check box. – vahancho Feb 18 '14 at 08:20
  • Could you provide a simple example of that usage. I couldn't find an example for using that flag. – Karen Tsirunyan Feb 18 '14 at 08:50
  • In your model reimplement `QAbstractItemModel::flags(const QModelIndex &) const` function that should return `return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable;` for checkable nodes. – vahancho Feb 18 '14 at 09:01
  • And don't forget to set default value: `model()->data( Qt::Unchecked, Qt::CheckStateRole );` – Dmitry Sazonov Feb 18 '14 at 09:23
  • P.S. if you preffer custom drawing you may check this answer - http://stackoverflow.com/a/16301316/1035613 – Dmitry Sazonov Feb 18 '14 at 09:30

0 Answers0