qt如何设置tableview鼠标悬浮选中一行
时间: 2024-05-11 08:19:53 浏览: 9
要实现鼠标悬浮选中一行,可以通过继承 QStyledItemDelegate 类来实现自定义的 item delegate。以下是一个简单的实现方式:
1. 定义一个新的 item delegate 类,继承自 QStyledItemDelegate:
```cpp
class HoverHighlightDelegate : public QStyledItemDelegate
{
public:
HoverHighlightDelegate(QObject* parent = nullptr);
void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override;
bool editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index) override;
private:
QModelIndex m_hoveredIndex;
};
```
2. 重写 paint() 函数,在绘制每个 item 时根据当前鼠标悬浮的项来设置选中状态:
```cpp
void HoverHighlightDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
QStyleOptionViewItem newOption(option);
// 如果当前项被鼠标悬浮,则设置为选中状态
if (index == m_hoveredIndex) {
newOption.state |= QStyle::State_Selected;
}
QStyledItemDelegate::paint(painter, newOption, index);
}
```
3. 重写 editorEvent() 函数,监听鼠标事件并保存当前鼠标悬浮的项:
```cpp
bool HoverHighlightDelegate::editorEvent(QEvent* event, QAbstractItemModel* model, const QStyleOptionViewItem& option, const QModelIndex& index)
{
switch (event->type()) {
case QEvent::MouseMove:
m_hoveredIndex = index; // 记录当前鼠标悬浮的项
break;
case QEvent::Leave:
m_hoveredIndex = QModelIndex(); // 鼠标离开时清除记录
break;
}
return QStyledItemDelegate::editorEvent(event, model, option, index);
}
```
4. 在使用该 item delegate 的 table view 中设置该 delegate:
```cpp
HoverHighlightDelegate* delegate = new HoverHighlightDelegate(tableView);
tableView->setItemDelegate(delegate);
```
这样就能实现在鼠标悬浮时选中一行的效果了。如果需要自定义选中时的样式,可以在 paint() 函数中进一步修改 QStyleOptionViewItem 的属性。