如何在Qt中更改一种QBarSet条/元素颜色? [英] How to change one QBarSet bar/element color in qt?

查看:1163
本文介绍了如何在Qt中更改一种QBarSet条/元素颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将QBarSethovered信号连接到插槽,当鼠标悬停在条形集上时将更改QBarSet的颜色,并在鼠标离开时重置颜色.
该代码段如下所示:

I connected to the hovered signal of QBarSet to a slot, which will change the QBarSet color when mouse hovers on the bar set and reset the color when mouse leaves.
The code snippet looks like this:

void BarChart::hoverTest(bool status, int index)
{
    if(status == true) {
        set->setColor(Qt::red); //changes to bar set color to red mouse when hovers on bar set
    }
    else {
        set->setColor(QColor(52, 152, 219)); //reset the color when mouse leaves
    }
}

这些是悬停前和悬停时的图片:

And those are the pics before hovering and when hovers:

如您所见,如果我将鼠标悬停在条形图集上,则所有这些条形图集的条形(元素)颜色都将变为红色.但是我想将鼠标悬停在条形图组的特定条形图(元素)上,并且该条形图(元素)会更改其颜色,其余的保持不变.

有没有办法做到这一点?

As you can see, if I hover on the bar set, all this bar set bars(elements) color changed to red. But I want to hover on a specific bar(element) of the bar set, and that bar(element) changes its color, and the rest of them stay the same.

Is there a way to achieve this?

推荐答案

当前无法单独更改列的颜色,因此我将显示一种解决方法.这包括在悬浮的项目上方放置一个新项目,如下所示:

It is not currently possible to change the color of the column individually, so I will show a workaround. This consists of placing a new item on top of the hovered item as shown below:

#include <QApplication>
#include <QtCharts>
QT_CHARTS_USE_NAMESPACE

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QChartView w;

    QBarSet *set0 = new QBarSet("bar1");

    *set0 << 1 << 4 << 3 << 7 << 2 << 5 << 1 << 3 << 3 << 2 << 1 << 6 << 7 << 5;

    QBarSeries *series = new QBarSeries;
    series->append(set0);

    QChart *chart= new QChart;
    w.setChart(chart);
    chart->addSeries(series);
    w.show();

    QGraphicsRectItem hoverItem;
    hoverItem.setBrush(QBrush(Qt::red));
    hoverItem.setPen(Qt::NoPen);

    QObject::connect(set0, &QBarSet::hovered, [&w, &hoverItem](bool status, int /*index*/){
        QPoint p = w.mapFromGlobal(QCursor::pos());
        if(status){
            QGraphicsItem *it = w.itemAt(p);
            hoverItem.setParentItem(it);
            hoverItem.setRect(it->boundingRect());
            hoverItem.show();
        }
        else{
            hoverItem.setParentItem(nullptr);
            hoverItem.hide();
        }
    });
    return a.exec();
}

这篇关于如何在Qt中更改一种QBarSet条/元素颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆