3

I have used the qcustomplot to draw item.

I have two item. One is item text, another is item rect.

What I want to do is when I select the text, the item rect change the color.

I have used the itemAt to check whether the mouse has clicked a item.

But I have encountered two problems

  1. I don't know what item text I selected.

  2. I don't know how to find the specific item rect by name.

Code:

//item text
QCPItemText *text= new QCPItemText(ui->customPlot);
ui->customPlot->addItem(text);
text->setSelectable(true);
text->position->setCoords(10, 30);
text->setText("text");
text->setFont(QFont(font().family(), 9));

// item rect
QCPItemRect *rect= new QCPItemRect(ui->customPlot);
ui->customPlot->addItem(rect);
rect->setPen(QPen(QColor(50, 0, 0, 100)));
rect->setSelectedPen(QPen(QColor(0, 255, 0, 100)));
rect->setBrush(QBrush(QColor(50, 0, 0, 100)));
rect->setSelectedBrush(QBrush(QColor(0, 255, 0, 100)));
rect->topLeft->setCoords(0,10);
rect->bottomRight->setCoords(10,0);
connect(ui->customPlot, SIGNAL(mouseMove(QMouseEvent*)), this, SLOT(moveOver(QMouseEvent*)));


moveOver(QMouseEvent* event)
{
    QPoint pos = event->pos();
    QCPAbstractItem *item = ui->customPlot->itemAt(pos, true);
    if(item != 0) qDebug() << "moved over";
}
Jason
  • 1,573
  • 3
  • 18
  • 46

1 Answers1

1

First, in order to change rect color inside your moveOver event you can save it as a data member of the class.

Second, because both QCPItemRect and QCPItemText inherits from QCPAbstractItem you can use dynamic_cast. You can try to cast it to QCPItemText and if the cast will fail your pointer will be null. Take a look also at this post.

So, your code should look like:

moveOver(QMouseEvent* event)
{
    QPoint pos = event->pos();
    QCPAbstractItem *item = ui->customPlot->itemAt(pos, true);
    textItem = QCPItemText* dynamic_cast<QCPItemText*> (item);
    if (textItem == 0){
        //item is not a QCPItemText
        **do something**
    }
    else{
        //item is a QCPItemText - change rect color
        rect->setBrush(QBrush(QColor(50, 0, 0, 100)));
    }
}
Community
  • 1
  • 1
A. Sarid
  • 3,916
  • 2
  • 31
  • 56