我正在用PyQt写一个程序。我使用QTableView来显示数据。
问题是,当我触发单元格的编辑(例如按F2)时,默认情况下单元格中的文本都被选中(突出显示)。这并不方便,因为我想修改文本,而不是全部重写。
所以我想知道有没有什么函数可以改变行为?
谢谢
发布于 2012-07-03 16:46:27
不确定是否有更简单的方法,但您可以编写自己的项目委托来创建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。
发布于 2012-07-03 16:41:39
您需要实现一个委托,以便可以覆盖用于编辑该字段的小部件,以使用自定义编辑器小部件。
默认情况下,QTableView将使用QTextEdit,您可以尝试将其子类化并更改其行为。我最好的猜测是,您需要在编辑器小部件(可能是focusInEvent1 )上操作焦点策略,以更改它在接收焦点时的行为。
1
https://stackoverflow.com/questions/11298245
复制相似问题