一、前言
上篇文章介绍了如何调用qt自带的颜色画板,其实目的就是想更改一些颜色,本篇博客介绍更改QCustomPlot的曲线颜色
二、环境
qt5.7 mingw
windows8
sqlite3
三、正文
- 首先在数据库中建好表,一行多列,放置多个颜色值
- 在QCustomPlot初始化最后加上
CustomPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom| QCP::iSelectAxes | QCP::iSelectLegend | QCP::iSelectPlottables);//可以进行鼠标位置 放大缩小 拖拽 放大缩小坐标系!!!功能非常强大 CustomPlot->legend->setSelectableParts(QCPLegend::spItems); connect(CustomPlot, SIGNAL(selectionChangedByUser()), this, SLOT(selectionChanged()));
点击曲线标题回调出颜色面板
void MainWindow::selectionChanged() { for (int i=0; i<ui->widget1->graphCount(); ++i){ QCPGraph *graph = ui->widget1->graph(i); QCPPlottableLegendItem *item = ui->widget1->legend->itemWithPlottable(graph); if (item->selected()/*||graph->selected()*/){ QColorDialog *m_pColor = new QColorDialog(this); m_pColor->setWindowModality(Qt::ApplicationModal); m_pColor->setCurrentColor(QColor(Qt::red));//初始颜色 m_pColor->show(); m_pColor->move(720,200); connect(m_pColor,SIGNAL(currentColorChanged(QColor)),this,SLOT(ShowColor(QColor)));//显示当前选中颜色的效果 connect(m_pColor,SIGNAL(colorSelected(QColor)),this,SLOT(SetColor(QColor)));//OK信号连接 } } }
颜色面板对应的确认拾取函数
-
void MainWindow::ShowColor(const QColor &color)//只要当前颜色在对话框中发生改变,就会触发该信号。 { qDebug()<<"1111"<<color; } void MainWindow::SetColor(const QColor &color)//当用户选中某一颜色并点击“OK”后,就会触发该信号。 { QStringList hexStr; for(int i=0; i<ui->widget1->graphCount(); ++i){ QCPGraph *graph = ui->widget1->graph(i); QCPPlottableLegendItem *item = ui->widget1->legend->itemWithPlottable(graph); if(item->selected()/*|| graph->selected()*/) graph->setPen(QPen(color)); QString redStr = QString("%1").arg(graph->pen().color().red(),2,16,QChar('0')); QString greenStr = QString("%1").arg(graph->pen().color().green(),2,16,QChar('0')); QString blueStr = QString("%1").arg(graph->pen().color().blue(),2,16,QChar('0')); hexStr.append("#"+redStr+greenStr+blueStr); } QSqlTableModel *model = new QSqlTableModel(NULL, db); model->setTable("xxx"); model->setEditStrategy(QSqlTableModel::OnManualSubmit); model->select(); QSqlRecord record = model->record(); record.setValue("graph1",hexStr.at(0)); record.setValue("graph2",hexStr.at(1)); record.setValue("graph3",hexStr.at(2)); record.setValue("graph4",hexStr.at(3)); model->setRecord(0, record);//修改的行 row_forsql model->submitAll(); }
到此就完成一大半了,拾取颜色改变颜色已经完成,最后还差初始化时将上次的颜色刷新到曲线中,用读取数据库的方式。在曲线初始化前获取颜色
-
QStringList colorlist; QSqlQuery qry(db); if(qry.exec("select * from xxx")&&qry.next()){ for(int i=0;i<4;i++)colorlist.append(qry.value(i).toString()); }
四、结语
大功告成