How to align a checkbox added in column of a QTAbleView using QItemDelegate
-
Hi All,
Thanks in advance for the help. Is there any way to fix the alignment of a checkbox added in one of the column in a QTableView.
Using QitemDelegate to create the checkbox using createEditor:
QWidget *NetDiagnosticsSelectionItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem
&option, const QModelIndex &index) const
{
QCheckBox *checkBox = new QCheckBox(parent);
return checkBox;
}I am getting a left aligned QCheckBox
-
Return a QWidget which contains two spacers and a QCheckbox in between.
-
@Christian-Ehrlicher
Thanks for the response. I am yet to try this approach but is 9it the only way to do it?Why my below code in data(const QModelIndex & index, int role) doesnt work for only the column having checkboxes??
if (role == Qt::TextAlignmentRole)
return Qt::AlignCenter; -
The checkbox is not getting created using the QItem delegate. But its due to the following code in QVariant data(const QModelIndex & index, int role){
if (role == Qt::CheckStateRole)
{
if (index.column() == Selection)
{
NetDiagnosticsInfo *value = netDiagnosticsValues_.at(index.row());
bool aBool = value->getSelection();
if (aBool)
return Qt::Checked ;
else
return Qt::Unchecked ;
}
}
}Is there any way to set the alignment here?
-
No, Qt does not support aligning the checkbox in the item. You have to do it in your own delegate the way I told you above.
-
@Christian-Ehrlicher Not working . The checkbox disappered when i added the checkox using a createEditor.
QWidget *NetDiagnosticsSelectionItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem
&option, const QModelIndex &index) const
{
QCheckBox *checkBox = new QCheckBox(parent);
return checkBox;
}ui->tableView->setItemDelegateForColumn(NetDiagnosticsModel::Selection, new NetDiagnosticsSelectionItemDelegate(this));
Should i use paint function and not create editor???
-
I had the same problem which I'd left open for years. Lately I revisited it and came up with these simple tweaks that seem working to me. I hope someone may find them useful.
// relocate checkbox to cell center
void CheckItemDelegate::drawCheck ( QPainter * painter, const QStyleOptionViewItem & option, const QRect & rect,
Qt::CheckState state ) const
{
int dx = (option.rect.width() - rect.width()) / 2;QRect adjRect = rect; adjRect.adjust(dx, 0, dx, 0); QItemDelegate::drawCheck(painter, option, adjRect, state);
}
// suppress drawing of the background of the empty text which would otherwise cover the relocated checkbox
void CheckItemDelegate::drawDisplay(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect, const QString &text) const
{
}// draw focus frame around the entire cell instead of just the text
void CheckItemDelegate::drawFocus(QPainter *painter, const QStyleOptionViewItem &option, const QRect &rect) const {
QItemDelegate::drawFocus(painter, option, option.rect);
}