Select partial text inside QTableWidget cell
-
How can I programmatically select parital text inside a QTableWidget cell?
I would like to implement a Find-function so that the user can search for a string. The first match shall be selected in the cell of table.
Thanks,
Tobi -
Hi, welcome to devnet
The default implementation selects cells, not text and the only time text is selected is if the item is editable.
Do you want to enter the edit mode and select the part you need or paint the selection on selected cell? In case of the latter you would have to implement a custom cell delegate. -
I would like to enter the edit mode and select a part of the text. Like if the user double clicks on the cell and select the last three letters.
-
The default delegate does not provide a way to get to the underlying line edit so you would have to create a delegate that does.
A very (very!) crude example would be something like this:
@
class MyDelegate : public QStyledItemDelegate {
public:
MyDelegate(QObject* parent = nullptr) : QStyledItemDelegate(parent) {}
void setEditorData(QWidget editor, const QModelIndex &index) const {
QStyledItemDelegate::setEditorData(editor, index);
lineEdit = qobject_cast<QLineEdit>(editor);
}
mutable QLineEdit* lineEdit;
};//then set it:
tableWidget->setItemDelegate(new MyDelegate(tableWidget));//and use it:
tableWidget->editItem(item);
auto le = static_cast<MyDelegate*>(tableWidget->itemDelegate())->lineEdit;
if(le) le->setSelection(4,2);
@but please don't do it exactly like this. It's just an example. The delegate should create your own line edit and keep track of the pointer. The "mutable" there is also an ugly hack. This is just to give you an idea.
-
Thanks Chris for your example. I did it with the 'ugly hack'. What do you mean with "The delegate should create your own line edit and keep track of the pointer" ?
-
bq. I did it with the ‘ugly hack’.
Please don't ;)
bq. What do you mean with “The delegate should create your own line edit and keep track of the pointer” ?
The example is based on the assumption that the createEditor() method of QStyledItemDelegate actually creates a QLineEdit. Although it's unlikely to change it's non the less only an assumption true just for the current Qt version. If it happens to change in the future for e.g. QTextEdit it will stop to work.
You should override the createEditor() method and create QLineEdit (or whatever you wish) yourself to be sure it's what you expect it to be. This way you wouldn't even need the setEditorData() method for the cast because you could directly hold to the line edit you created in createEditor().