3

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

officialhopsof
  • 173
  • 2
  • 9
  • Did you try to put a `QTextWidget` into table cells with proper restrictions? – VP. Jan 29 '15 at 20:16
  • Could you provide a link to the documentation to `QTextWidget` ? I cannot seem to find it. – officialhopsof Jan 29 '15 at 20:27
  • Oops, I meant `QTextEdit`. Also you may try to put `QLabel` which allows user selection. – VP. Jan 29 '15 at 20:28
  • I did try both of those with some minor success but then the selection of cells acted very odd. Basically when I clicked on a cell that used the QLabel, the table selection would not change. – officialhopsof Jan 29 '15 at 20:30

2 Answers2

1

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.

UmNyobe
  • 22,539
  • 9
  • 61
  • 90
  • But I want the user to be able to open the text edit of every item, so they can copy a small section out of the cell. I just want any changes made to instantly be reverted or to disable editing in the text edit – officialhopsof May 18 '15 at 18:59
1

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.

rickbsgu
  • 157
  • 1
  • 3