I was little bit searching and trying to make it work and it can be changed by casting QGraphicsItem
to QGraphicsRectItem
.
It is similar as in previous answer:
QObject::connect(set0, &QBarSet::hovered, [&w](bool status, int /*index*/){
QPoint p = w.mapFromGlobal(QCursor::pos());
if(status){
QGraphicsRectItem *rect = qgraphicsitem_cast<QGraphicsRectItem *>(w.itemAt(p));
rect->brush().setColor(Qt::red);
rect->update();
}
else{
rect->brush().setColor(Qt::blue); //or change it to default colour
rect->update();
}
});
Additionally, it is possible use index of QBarSet::hovered
but that take lot of work and it is not possible do it directly. In my case I created method to find all bar graphic objects in chart and sort them by x position so the indices in QObject::connect
corresponds to sorted list.
So at first, we need to find all bars in a chart and cast the into QGraphicsRectItem
and sort them.
void sortGraphicItems( std::vector<std::pair<float,QGraphicsRectItem*> > &item_list){
for(int i = 0; i<this->items().size();i++){
if(w->items().at(i)->flags().testFlag(QGraphicsItem::ItemIsSelectable)){ //This selects all selectable items
QGraphicsRectItem *it = qgraphicsitem_cast<QGraphicsRectItem *>(this->items().at(i));
if (!it) //if the graphic object is not type of QGraphicsRectItem
continue;
item_list.push_back( std::make_pair(it->rect().x(), it) );
}
}
std::sort(item_list.begin(),item_list.end());
}
and then just do the same but use index of QBarset
.
QObject::connect(set0, &QBarSet::hovered, [&w](bool status, int ind){
if(status){
std::vector<std::pair<float,QGraphicsRectItem*> > item_list;
sortGraphicItems(item_list);
QGraphicsRectItem *rect = item_list.at(ind).second;
//change colour of rect
}
else{
//change rect colour back
}