20200519-01 QCustomPlot 關於標籤拖動

一、前言:

推薦閱讀內容

https://www.cnblogs.com/swarmbees/p/6058263.html

https://www.cnblogs.com/xiongxuanwen/p/10102301.html

以及官方文檔

 

二、正文

//新建一個標籤

    m_label = new QCPItemText(m_plot);
    m_label->setClipToAxisRect(false);
    m_label->setPadding(QMargins(5, 5, 5, 5));
    m_label->setBrush(QBrush(Qt::NoBrush));
    m_label->setPen(QPen(QColor(Qt::red)));
    m_label->setFont(QFont("Arial", 8));
    m_label->setColor(Qt::black);
    m_label->setText("Test");
    m_label->setPositionAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    m_label->setSelectedBrush(QBrush(Qt::green));
    //使能可選中
    m_label->setSelectable(true);


//使能可選中,這裏 QCP::iSelectItems 可以令像 Text/Line 這類控件能夠被選中
    m_customplot->setInteractions(QCP::iSelectItems);

//選中之後可以這個函數獲取選中項
    m_customplot->selectedItems();

//重新實例化鼠標事件
void QCustomLine::mousePressEvent(QMouseEvent *event)
{
    QCustomPlot::mousePressEvent(event);

    //默認設置同時只能選中一個,所以選取第一個對象
    if (m_customplot->selectedItems().isEmpty())
        return;
    temp_selected = dynamic_cast<QCPItemText*>(m_customplot->
                    selectedItems().value(0);
}

void QCustomLine::mouseMoveEvent(QMouseEvent *event)
{
    routeMouseEvents(event);
    // 選中時候移動
    if (temp_selected) {

        temp_selected->setCoords(m_customplot->xAxis->pixelToCoord(event->x()),
                                 m_customplot->yAxis->pixelToCoord(event->y()));
        m_customplot->replot();
    }
}

void QCustomLine::mouseReleaseEvent(QMouseEvent *event)
{
    routeMouseEvents(event);

    temp_selected = nullptr;
    qDebug() << "----released!";
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章