QTableWidget或QTableWidgetItem存在以下问题:
我想在单元格的编辑/键入期间对其进行分析,
例如,作为对KeyReleaseEvent的反应。

但是QTableWidgetItem :: text()属性仅在
单元格编辑完成(焦点已离开单元格)。

我该如何克服这种行为?当然,可以分析
KeyReleaseEvent中的按钮按键,但是使用text()属性,它将更加容易...

最佳答案

一种可能的解决方案是通过委托建立自定义QLineEdit作为编辑器:

#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();
}

关于c++ - QTableWidgetItem text()属性在编辑期间,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59323399/

10-12 18:04