查找了很多文章,大多数是以下这句,但本人在代码中添加下面这句代码,并不生效!
ui->tableWidget->item(num,0)->setFlags(Qt::NoItemFlags);
于是,又找了更多的代码去尝试,尝试有效果的代码:
// 设置0列只读
ReadOnlyDelegate* readOnlyDelegate = new ReadOnlyDelegate(this);
ui->tableWidget->setItemDelegateForColumn(0, readOnlyDelegate);
ui->tableWidget->setItemDelegateForColumn(1, readOnlyDelegate);
ui->tableWidget->setItemDelegateForColumn(2, readOnlyDelegate);
其中,delegate为:
// 设置tableview某行/列不可编辑,
class ReadOnlyDelegate: public QItemDelegate
{
public:
ReadOnlyDelegate(QWidget *parent = NULL):QItemDelegate(parent)
{}
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,const QModelIndex &index) const override;
};
实现为:
#include "readonlydelegate.h"
QWidget *ReadOnlyDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const //final
{
Q_UNUSED(parent)
Q_UNUSED(option)
Q_UNUSED(index)
return NULL;
}