我正在使用PyQt编写一个程序,使用QTableView显示数据。问题是当我触发单元格的编辑(例如按下F2)时,默认情况下会选择(高亮)单元格中的文本。这很不方便,因为我想修改文本而不是全部重写。所以我想知道是否有任何函数可以改变这种行为?
谢谢!
谢谢!
不确定是否有更简单的方法,但您可以编写自己的项委托来创建一个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);
}
您需要实现一个委托,以便可以覆盖用于编辑该字段的小部件,以使用自定义编辑器小部件。
QTableView默认使用QTextEdit,您可以尝试对其进行子类化并更改其行为。我最好的猜测是,您需要操纵编辑器小部件上的焦点策略,可能是focusInEvent[1],以在接收焦点时更改其行为。