gpt4 book ai didi

qtableview文本编辑

转载 作者:行者123 更新时间:2023-12-04 13:28:22 25 4
gpt4 key购买 nike


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

谢谢

最佳答案

不确定是否有更简单的方法,但您可以编写自己的项目委托(delegate)来创建 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 文档中使用过委托(delegate),那么有一个有用的 example .

关于qtableview文本编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11298245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com