【问题标题】:qtableview text editqtableview 文本编辑
【发布时间】:2012-07-02 17:20:14
【问题描述】:


我正在用 PyQt 编写一个程序。我使用 QTableView 来显示数据。
问题是当我触发单元格的编辑(例如按 F2)时,默认情况下单元格中的文本全部被选中(突出显示)。这不方便,因为我想修改文本而不是全部重写。
所以我想知道是否有任何功能可以改变行为?

谢谢

【问题讨论】:

    标签: qt pyqt qtableview


    【解决方案1】:

    不确定是否有更简单的方法,但您可以编写自己的项目委托来创建 QLineEdit。使用模型数据更新编辑器时,您取消选择文本并可能将光标移动到开头。委托是这样的(我现在没有可用的 Qt 安装,所以我无法测试它,但这个想法应该可行):

    QWidget * MyDelegate::createEditor(QWidget *parent,
            const QStyleOptionViewItem & option,
            const QModelIndex & index) const
    {
        // Just creates a plain line edit.
        QLineEdit *editor = new QLineEdit(parent);
        return editor;
    }
    
    void MyDelegate::setEditorData(QWidget *editor,
            const QModelIndex &index) const
    {
        // Fetch current data from model.
        QString value = index.model()->data(index, Qt::EditRole).toString();
    
        // Set line edit text to current data.
        QLineEdit * lineEdit = static_cast<QLineEdit*>(editor);
        lineEdit->setText(value);
    
        // Deselect text.
        lineEdit->deselect();
    
        // Move the cursor to the beginning.
        lineEdit->setCursorPosition(0);
    }
    
    void MyDelegate::setModelData(QWidget *editor,
            QAbstractItemModel *model,
            const QModelIndex &index) const
    {
        // Set the model data with the text in line edit.
        QLineEdit * lineEdit = static_cast<QLineEdit*>(editor);
        QString value = lineEdit.text();
        model->setData(index, value, Qt::EditRole);
    }
    

    如果您之前没有在 Qt 文档中使用过委托,那么有一个有用的 example

    【讨论】:

    • 非常感谢。很有帮助。
    【解决方案2】:

    您需要实现一个委托,以便您可以覆盖用于编辑该字段的小部件以使用自定义编辑器小部件。

    默认情况下 QTableView 将使用 QTextEdit,您可以尝试对其进行子类化并更改其行为。我最好的猜测是您需要在编辑器小部件上操作焦点策略,可能是 focusInEvent[1],以更改它在接收焦点时的行为。

    [1]http://doc.qt.nokia.com/4.7/qwidget.html#focusInEvent

    【讨论】:

      猜你喜欢
      • 2012-02-06
      • 1970-01-01
      • 2012-01-18
      • 1970-01-01
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多