PDA

View Full Version : QTableWidgetItem and setCheckState



rmagro
22nd March 2012, 10:37
Hi guys,
I’m using a QTableWidget structure in which the first column is used as a check box.
Here the code:

for (int row_i=0; row_i < rows; ++row_i)
{
for (int column_j=0; column_j < 15; column_j++)
{
QTableWidgetItem *item = new QTableWidgetItem;
item->setText("");
item->setTextAlignment (Qt::AlignCenter);
tableWidget->setItem(row_i, column_j, item);
}
}

Then, for each row:

tableWidget->item(row, 0)->setCheckState ( Qt::Checked );

the problem is that when I select with the mouse the cell (first column for each row) besides the little square you can check or uncheck (precisely on the right side) it appears a rectangle about a text area..(see the image attached)
How can I get rid of this ?
Many thanks,
robby77

7524

ChiliPalmer
22nd March 2012, 11:58
Hi,

that rect is drawn because the item has focus. Because of your thread I noticed that I have the same problem with something similar I've done, so thanks ;)
I tried to get rid of it with item flags, but that didn't work. If you take out ItemIsSelectable the item won't be highlighted when clicking on it, but the rect will still be drawn. Taking out ItemIsEnabled prohibits the user from clicking the checkbox.

I guess the easiest solution would be to create a QStyledItemDelegate for that column, reimplement initStyleOption and do this:

QStyleOptionViewItemV4 *v4 = qstyleoption_cast<QStyleOptionViewItemV4 *>(option);
if (v4->state.testFlag(QStyle::State_HasFocus)) {
v4->state ^= QStyle::State_HasFocus;
}

rmagro
22nd March 2012, 15:01
Hi,
and thank you for your reply.
I've never manage with that stuff.. Can you provide me with the example about how to exploit your trick in my case ??
Have a nice day :)

rmagro
18th April 2012, 15:35
My solution:
in .h files:


class StyledItemDelegate : public QStyledItemDelegate
{
public:
StyledItemDelegate(QObject *parent = NULL) :
QStyledItemDelegate(parent) {}
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QStyleOptionViewItem opt = option;
opt.state &= ~QStyle::State_HasFocus;
QStyledItemDelegate::paint(painter, opt, index);
}
};


then in your code you have:



tableWidget->setItemDelegate(new StyledItemDelegate(this));

Meep
19th October 2016, 13:57
Old post, but here's a simpler solution:


tableWidget->setFocusPolicy(Qt::NoFocus);