你可以尝试以下代码来优化你的paintEvent函数,实现鼠标滑过和鼠标点击时的样式:
void CProjectList::paintEvent(QPaintEvent* event)
{
// 先调用父类的绘制函数
QTreeView::paintEvent(event);
QPainter painter(viewport());
for (QAction* action : menu->actions()) {
if (action->property("customStyle").toBool()) {
QRect rect = visualRect(indexAt(QPoint(0, 0)));
// 获取鼠标状态
bool isHovered = action->data().toBool();
bool isChecked = action->isChecked();
// 设置背景颜色和字体颜色
QColor bgColor;
QColor textColor;
if (isChecked) {
bgColor = QColor("#3F7AFF");
textColor = QColor("#F2F6FF");
} else if (isHovered) {
bgColor = QColor("#4C83FF");
textColor = Qt::black;
} else {
continue; // 非激活状态无需绘制
}
painter.fillRect(rect, bgColor); // 设置背景颜色
QString text = action->text();
// 绘制文本
painter.setPen(textColor);
painter.drawText(rect, Qt::AlignCenter, text);
}
}
}
在设置菜单项时,添加相应的信号槽连接以更新自定义属性值:
QAction* addAction = menu->addAction("添加样品", this, &CProjectList::slotAddItemInTreeSample);
connect(addAction, SIGNAL(hovered()), this, SLOT(actionHovered()));
connect(addAction, SIGNAL(toggled(bool)), this, SLOT(actionToggled(bool)));
然后,在CProjectList类中添加槽函数来处理鼠标悬停和选中状态变化的信号:
void CProjectList::actionHovered()
{
QAction* action = qobject_cast<QAction*>(sender());
if (action) {
action->setData(true);
viewport()->update(); // 更新绘制
}
}
void CProjectList::actionToggled(bool checked)
{
QAction* action = qobject_cast<QAction*>(sender());
if (action) {
action->setData(false);
action->setChecked(checked);
viewport()->update(); // 更新绘制
}
}
这样就可以实现鼠标滑过和鼠标点击时的不同样式了。如果有其他问题,请随时提问。
内容由零声教学AI助手提供,问题来源于学员提问