qt的tableview设置鼠标悬浮选中
时间: 2023-09-20 08:03:35 浏览: 65
要实现鼠标悬停选中QTableView中的行,你可以使用以下步骤:
1.创建一个自定义的QStyledItemDelegate子类,重写paint()和editorEvent()方法。
2.在paint()方法中,使用QStyleOptionViewItem类的state属性来检查当前单元格是否被鼠标悬停。如果是这样,使用QStyle的drawPrimitive()方法绘制所需的背景和前景。
3.在editorEvent()方法中,检查鼠标事件类型是否为QEvent::MouseMove和QEvent::MouseButtonPress。如果是这样,使用QModelIndex类的row()方法和QAbstractItemView类的selectRow()方法选择当前行。
下面是一个示例代码:
```
class HoverDelegate : public QStyledItemDelegate
{
public:
HoverDelegate(QObject *parent = nullptr) : QStyledItemDelegate(parent) {}
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override
{
QStyleOptionViewItem opt = option;
initStyleOption(&opt, index);
if (opt.state & QStyle::State_MouseOver) { // 检查鼠标是否悬停
painter->fillRect(opt.rect, opt.palette.highlight());
painter->setPen(opt.palette.highlightedText().color());
}
painter->drawText(opt.rect, Qt::AlignCenter, index.data(Qt::DisplayRole).toString());
}
bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) override
{
if (event->type() == QEvent::MouseMove || event->type() == QEvent::MouseButtonPress) {
QAbstractItemView *view = qobject_cast<QAbstractItemView *>(option.widget);
if (view) {
view->selectRow(index.row()); // 选择当前行
return true;
}
}
return QStyledItemDelegate::editorEvent(event, model, option, index);
}
};
```
然后,在你的QTableView中设置该委托:
```
HoverDelegate *delegate = new HoverDelegate(this);
ui->tableView->setItemDelegate(delegate);
```
这样,当鼠标悬浮在QTableView中的行上时,该行将被高亮显示,并可通过单击鼠标选择该行。