I have a custom QTableView
model with a custom QHeaderView
in order to render a checkbox used to perform a "select all" function on the table's contents.
In my header's overloaded paintSection()
function, I successfully render the checkbox used to select all with:
QStyleOptionButton option;
option.rect = QRect(3,10,16,16);
option.state = QStyle::State_Enabled | QStyle::State_Active;
if (isChecked_)
option.state |= QStyle::State_On;
else
option.state |= QStyle::State_Off;
style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &option, painter);
Unfortunately, the checkbox is not rendered centered, and instead justified left. This completely clashes with the properly-centered QStyledItemDelegate
checkboxes in the column for each table entry.
I know I can change the first two args of QRect
to change the origin of the drawn primitive, but this isn't responsive to changes in column width. Although, making the column width fixed isn't the worst solution.
How can I properly center the checkbox in the column header?
Ancillary question: the checkbox in the header is able to be toggled by clicking anywhere in the cell, not just on the box itself (unlike those rendered in the table via delegates). Is there a way to fix this?
The solution of @scopchanov does not work for me since the checkbox covers the whole item of the header
A possible solution is to draw the CheckBox with styles, but apart from that you have to keep a memory of whether the element is checked or not, for this we use
QMap<>
, the first element is thelogicalIndex
since it does not change even when it is move the columns and the second element is the state.