qcustomplot:按名称设置项目并找到它们

qcustomplot: set item by name and find them

我用qcustomplot画了item

我有两个项目。 一个是item text,另一个是item rect。

我想做的是当我 select 文本时,项目 rect 改变颜色。

我已经使用itemAt检查鼠标是否点击了一个项目。

但是遇到了两个问题

  1. 我不知道我 select编辑了什么项目文本。

  2. 我不知道如何按名称查找特定项目。

代码:

//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";
}

首先,为了在 moveOver 事件中更改 rect 颜色,您可以将其保存为 class.

的数据成员

其次,因为 QCPItemRectQCPItemText 都继承自 QCPAbstractItem 你可以使用 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.

因此,您的代码应如下所示:

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)));
    }
}