首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >qtableview文本编辑

qtableview文本编辑
EN

Stack Overflow用户
提问于 2012-07-03 01:20:14
回答 2查看 4.6K关注 0票数 3

我正在用PyQt写一个程序。我使用QTableView来显示数据。

问题是,当我触发单元格的编辑(例如按F2)时,默认情况下单元格中的文本都被选中(突出显示)。这并不方便,因为我想修改文本,而不是全部重写。

所以我想知道有没有什么函数可以改变行为?

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-07-03 16:46:27

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

代码语言:javascript
复制
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

票数 5
EN

Stack Overflow用户

发布于 2012-07-03 16:41:39

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

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

1

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11298245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档