可以通过设置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,这表示整行将被选中而不是单个单元格。这样,当单击单元格时,整个行将被选中。
