officialhopsof
officialhopsof

Reputation: 173

C++ QT: QTableWidget; how to let the user select text in a cell but not edit it

I am using a QTableWidget and I have a requirement that the user is able to highlight specific text in a cell, but the cell contents should not change if the user accidentally erases or modifies some cell contents. I was thinking that the simplest way to accomplish this would be to just ignore any edits that occur when the user finishes editing a cell. Any ideas how to do this?

Using C++ 98 and QT

Upvotes: 3

Views: 2983

Answers (2)

rickbsgu
rickbsgu

Reputation: 157

This is late, but for follow-on searches:

The best way to do this is to subclass a delegate (QStyledItemDelegate is the least problematic - no abstract virtuals).

In the delegate, override 'setModelData()' to a stub. The editor will still come up, and you can still change its contents, but the edit won't 'take'. As soon as you leave the cell, it will revert to its original contents.

If you want to prevent the editor from accepting keys (QLineEdit), override 'createEditor()' in your delegate. Call the base class to create an editor, check its type, and then install an event filter on the editor to reject keypress/keyrelease events.

Return the editor in your override.

Works for me, although I did have to const_cast 'this' (to non-const) to install the event filter.

Upvotes: 1

UmNyobe
UmNyobe

Reputation: 22890

You can access the table widget items and modify their properties You want to disable the Qt::ItemIsEditable flag :

QTableWidgetItem* item;
item->setFlags(item->flags() & ~(Qt::ItemIsEditable));

A good way is to set the item prototype before inserting cells into the table. Right after creating the table

const QtableItem* protoitem = table->itemPrototype();
QtableItem* newprotoitem = protoitem->clone();
newprotoitem->>setFlags(item->flags() & ~(Qt::ItemIsEditable));
table->setItemPrototype(newprotoitem);

Now every new cell in the table will have the editable flag disabled. If the user double click it will not open the text edit in the cell.

ps: Do not delete newprotoitem afterwards.

Upvotes: 1

Related Questions