I am surprised that such a hacker solution is recommended and used.
First: The validation state should be stored in the model. All tools already exist.
bool MyModel::setHeaderData(int index, Qt::Orientation orient, const QVariant& val, int role) { if(Qt::Vertical != orient) return Base::setHeaderData(index, orient, val, role); storeCheckState(index, val); emit headerDataChanged(orient, index, index); return true; } QVariant MyModel::headerData(int index, Qt::Orientation o, int role) const { if(Qt::Vertical != orient) return Base::headerData(index, o, role); switch(role) { ... case Qt::CheckStateRole: return fetchCheckState(index); } return Base::headerData(index, o, role); }
Second: We switch the checked state simply by processing the click signal on the header.
connect(header, &QHeaderView::sectionClicked, receiver , [receiver](int sec) { const auto index = logicalIndex(sec); model()->setHeaderData(index , Qt::Vertical , Qt::CheckState(model()->headerData(index, Qt::Vertical, Qt::CheckStateRole).toUInt()) != Qt::Checked ? Qt::Checked : Qt::Unchecked , Qt::CheckStateRole); });
Third: At this stage we fully functionally check the behavior, only a part is missing - this is visualization. The smartest way is to reuse the model using Qt::DecorationRole . Here is a dummy implementation:
QVariant MyModel::headerData(int index, Qt::Orientation o, int role) const { if(Qt::Vertical != orient) return Base::headerData(index, o, role); switch(role) { case Qt::DecorationRole: { QPixmap p{12,12}; p.fill(Qt::CheckState(headerData(index, o, Qt::CheckStateRole).toUInt()) ? Qt::green : Qt::red); return p; } break; ... } return Base::headerData(index, o, role); }
Of course, you can draw a real flag using a stylized drawing.
Please note that this solution does not require subclassification and custom widgets.
In addition, the verification state is separate from the / UI view. The only drawback is that the visual effects are processed by the model, but this is not necessary - any method can be used to draw the check state, including from alternative answers.