【问题标题】:QTableWidgetItem text() property during editing编辑期间的 QTableWidgetItem text() 属性
【发布时间】:2019-12-13 13:18:17
【问题描述】:

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

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

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

【问题讨论】:

    标签: c++ qt qtablewidget qtablewidgetitem


    【解决方案1】:

    一种可能的解决方案是通过委托建立一个自定义的 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();
    }
    

    【讨论】:

    • 谢谢,看来可以了!还有一个问题:如何从 LineEdit 访问原始 TableWidget?
    猜你喜欢
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 2011-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多