qcustomplot使用鼠標點擊選中多個點


使用qcustomplot類來實現對多個物體的選擇

 

如圖所示,我畫了一個散點圖,現在我想要實現使用鼠標點擊選中某些點的功能

 

 

 如上圖所示,代碼如下(附帶詳細注釋):

 1 void MainWindow::myPaint(QCustomPlot *customPlot)  2 {  3  QPen pen;  4     pen.setColor(QColor(255,0,0));  5     pen.setWidth(10);  6     customPlot->addGraph();  7     customPlot->graph(0)->setLineStyle(QCPGraph::lsNone);  //取消點與點之間的連線  8     customPlot->graph(0)->setPen(pen);  9     customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, 8));  //設置散點為圓點 10     QVector<double> x(10), y(10); 11     qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime())); 12 
13     for (int i=0;i<10;i++) { 14         x[i]=i; 15         y[i]=i+qrand()%20; 16  } 17 
18     customPlot->graph(0)->setData(x,y); 19     customPlot->graph(0)->rescaleAxes();
37 
38     customPlot->graph(0)->setSelectable(QCP::stDataRange); 39     customPlot->setMultiSelectModifier(Qt::KeyboardModifier::ControlModifier); 40     //在設置選擇多個點的時候首先要設置繪圖板是可選擇的(QCP::iSelectPlottables),然后再設置可選擇多個物體(QCP::iMultiSelect)
41     customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables | QCP::iMultiSelect);
43     customPlot->replot(); 44 }
customPlot->graph(0)->setSelectable(QCP::stDataRange);
設置選擇的方式,官方文檔有詳細的介紹:

 

customPlot->setMultiSelectModifier(Qt::KeyboardModifier::ControlModifier);

 官方文檔中說該函數是用來設置多選時的調節器的(翻譯水平有限,見諒),具體什么意思呢?

就是說我們在按住你設置的鍵之后就可以進行多選了,我這里設置為符合日常操作的ctrl鍵。

按照官方的說法,我們需要在setinteractions函數中設置QCP::iMultiSelect多選屬性,如下圖所示:

 

 當然錯誤是無法避免的,一開始我只是設置了這個屬性,運行之后發現在散點上點擊無響應,后來才知道需要設置圖層可選中即QCP::iSelectPlottables

因為散點是位於圖層之上的,那么如果圖層都無法選擇又怎么可以選擇散點呢?

水平有限,如有錯誤,還望指正,多謝閱讀!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM