我的做法是实现一个委托(delegate),然后把它设给你要只读的列
class ReadOnlyDelegate: public QItemDelegate
{
public:
ReadOnlyDelegate(QWidget *parent = NULL):QItemDelegate(parent)
{}
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const override //final
{
Q_UNUSED(parent)
Q_UNUSED(option)
Q_UNUSED(index)
return NULL;
}
};
很简单,就是不返回任何editor。
然后
ReadOnlyDelegate* readOnlyDelegate = new ReadOnlyDelegate();
ui->tableView->setItemDelegateForColumn(2, readOnlyDelegate); //设置某列只读
ui->tableView->setItemDelegateForRow(0, readOnlyDelegate); //设置某行只读
注意:QTableWidget设置某列不可编辑可以使用如下方法:
QTableWidgetItem* item0 = new QTableWidgetItem();
item0->setFlags(item0->flags() & (~Qt::ItemIsEditable));
ui->tableWidget->setItem(nRow, 0, item0);
//可参考:https://blog.csdn.net/sazass/article/details/114067748