Search code examples
c++qtqtablewidgetqtablewidgetitem

QTableWidgetItem text() property during editing


I have the following problem with the QTableWidget or QTableWidgetItem: I would like to analyze the text in the cell during its editing/typing, for example as a reaction on KeyReleaseEvent.

However the QTableWidgetItem::text() property is changed only AFTER the cell editing is finished (focus has left the cell).

How can I overcome such behavior? Of course, it is possible to analyze the button keys in the KeyReleaseEvent, but with the text() property it would be much easier...


Solution

  • One possible solution is to establish a custom QLineEdit as editor through the delegate:

    #include <QtWidgets>
    
    class LineEdit: public QLineEdit{
    public:
        using QLineEdit::QLineEdit;
    protected:
        void keyReleaseEvent(QKeyEvent *event) {
            QLineEdit::keyPressEvent(event);
            qDebug() << text();
        }
    };
    
    class StyledItemDelegate: public QStyledItemDelegate{
    public:
        using QStyledItemDelegate::QStyledItemDelegate;
        QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &) const{
            LineEdit *editor = new LineEdit(parent);
            return editor;
        }
    };
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        QTableWidget w(10, 10);
        w.setItemDelegate(new StyledItemDelegate(&w));
        w.show();
        return a.exec();
    }