Qt cpp WARAugmentedRealityOneSenceCoverLabelItemIcon paintEvent中绘制 图标在上方,文字在图标下方。均横向居中,文字加图标组合 竖向居中。且鼠标悬浮于文字图标时 ,图标文字显示不同颜色
时间: 2024-02-09 17:12:05 浏览: 28
好的,根据您的需求,下面是完整的代码示例:
```
void WARAugmentedRealityOneSenceCoverLabelItemIcon::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing, true);
QFont font = QFont("Microsoft YaHei", 12);
painter.setFont(font);
QPixmap iconPixmap = QPixmap(":/images/icon.png");
int iconWidth = iconPixmap.width();
int iconHeight = iconPixmap.height();
int textWidth = fontMetrics().width(m_text);
int textHeight = fontMetrics().height();
int totalWidth = qMax(iconWidth, textWidth);
int totalHeight = iconHeight + 10 + textHeight;
int x = (width() - totalWidth) / 2;
int y = (height() - totalHeight) / 2;
int iconX = x + (totalWidth - iconWidth) / 2;
int iconY = y;
int textX = x + (totalWidth - textWidth) / 2;
int textY = iconY + iconHeight + 10 + fontMetrics().ascent();
painter.setPen(Qt::NoPen);
// 鼠标悬浮于文字图标上方
if (m_hovered) {
painter.setBrush(QColor("#f2f2f2"));
painter.drawRoundedRect(x, y, totalWidth, totalHeight, 5, 5);
painter.setPen(QColor("#333"));
}
// 不可用状态
if (!isEnabled()) {
painter.setOpacity(0.5);
}
// 绘制图标和文字
painter.drawPixmap(iconX, iconY, iconPixmap);
painter.drawText(textX, textY, m_text);
painter.setOpacity(1.0);
}
void WARAugmentedRealityOneSenceCoverLabelItemIcon::enterEvent(QEvent *event)
{
Q_UNUSED(event);
m_hovered = true;
update();
}
void WARAugmentedRealityOneSenceCoverLabelItemIcon::leaveEvent(QEvent *event)
{
Q_UNUSED(event);
m_hovered = false;
update();
}
```
这个示例和上一个示例的区别在于,只有当鼠标悬浮于文字图标的上方时,才会显示不同的颜色。因此,在paintEvent中的判断条件变为了`if (m_hovered)`。如果您需要在鼠标悬浮于任何地方时都显示不同颜色,可以将判断条件改为`if (underMouse())`。
希望这份代码示例能够满足您的需求!
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)