PDA

View Full Version : How to centering the checkbox in qtableview



nemesisqp
8th April 2010, 14:57
hello, I want to draw a checkbox centered in the cell so I tried to subclass QStyledItemDelegate to draw the checkbox but it showed but won't centered and I tried to calculate QStyleOptionButton 's rect manually and it seem not the right way do to, so what is the right way to align item ? and one more problem I can't find a way to custom draw the header of qtableview , please help.


void TestDelegate::paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
if (index.column() == 1)
{
bool data = index.model()->data(index, Qt::DisplayRole).toBool();
QStyleOptionButton checkboxstyle;
checkboxstyle.rect = option.rect;
int width = checkboxstyle.rect.width();
checkboxstyle.rect.setLeft(checkboxstyle.rect.x()+ width/2);
if(data)
checkboxstyle.state = QStyle::State_On|QStyle::State_Enabled;
else
checkboxstyle.state = QStyle::State_Off|QStyle::State_Enabled;
QApplication::style()->drawControl(QStyle::CE_CheckBox, &checkboxstyle, painter);
}
else
{
QStyledItemDelegate::paint(painter, option, index);
}
}

nemesisqp
8th April 2010, 17:22
I just got it done, hope this will work in general case

void TestDelegate::paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
if (index.column() == 1)
{
bool data = index.model()->data(index, Qt::DisplayRole).toBool();
QStyleOptionButton checkboxstyle;
QRect checkbox_rect = QApplication::style()->subElementRect(QStyle::SE_CheckBoxIndicator, &checkboxstyle);
checkboxstyle.rect = option.rect;
checkboxstyle.rect.setLeft(option.rect.x() +
option.rect.width()/2 - checkbox_rect.width()/2);
if(data)
checkboxstyle.state = QStyle::State_On|QStyle::State_Enabled;
else
checkboxstyle.state = QStyle::State_Off|QStyle::State_Enabled;

QApplication::style()->drawControl(QStyle::CE_CheckBox, &checkboxstyle, painter);
}
else
{
QStyledItemDelegate::paint(painter, option, index);
}
}