Qt QTableview焦点设置为选中当前单元格

可以通过设置QTableView的selectionBehavior属性为QAbstractItemView::SelectItems来实现选中当前单元格。具体代码如下:

tableview->setSelectionBehavior(QAbstractItemView::SelectItems);
tableview->setCurrentIndex(tableview->currentIndex());

其中,setCurrentIndex函数将当前选中的单元格设置为当前焦点。注意,如果要保持选中状态,需要将QTableView的selectionMode属性设置为QAbstractItemView::SingleSelection,表示只能选择一个单元格。


相关问题

Qt QTableview怎么设置某个单元格不能选择

你可以通过自定义QStyledItemDelegate类,重写其paint函数:

class MyItemDelegate : public QStyledItemDelegate
{
public:
	myItemDelegate(QObject * parent = nullptr)
		:QStyleItemDelegate(parent)
	{
	}

	void paint(QPainter * painter,const QStyleOptionViewItem&option,const QModelIndex&index) const override
	{
		//调用父类 paint 函数绘制单元格
		QStyleItemDelegate::paint(painter,option,index);

		//如果是需要禁止选择的单元格,则绘制一个覆盖在上面的半透明矩形
		if(index.row() == 1 &&index.column() == 1)//这里以第2行第2列的单元格为例
		{
			painter->save();
			painter->setOpacity(0.5);
			painter->fillRect(option.rect,QColor(255 , 255, 255));
			painter->restore();
		}
	}
};

2.在需要使用QTableView的地方,创建一个实例化的MyItemDelegate对象,并将其设置为QTableView的ItemDelegate:

//创建QTableView对象
QTableView * tableView = new QTableView(this);

//创建一个实例化的MyItemDelegate对象
MyItemDelegate * itemDelegate = new MyItemDelegate(this);

//将MyItemDelegate 对象设置为QTableView 的 ItemDelegate
tableView->setItemDelegate(itemDelegate);

这样,就可以实现禁止选择某个单元格的功能了。在上面例子中,第2行第2列的单元格将无法被选择。

qt QtableView设置整行选中

要设置QTableView中的整行选中,可以使用以下代码:

//设置整行选中
tableView.setSelectionBehavior(QAbstractItemView::SelectRows);

在这里,我们使用setSelectionBehavior()方法设置QAbstractItemView::SelectionRows,这表示整行将被选中而不是单个单元格。这样,当单击单元格时,整个行将被选中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值