Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. How to set colors for LineSeries in QtGraphs using C++
Forum Updated to NodeBB v4.3 + New Features

How to set colors for LineSeries in QtGraphs using C++

Scheduled Pinned Locked Moved Solved General and Desktop
2 Posts 1 Posters 312 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • BugSleeperB Offline
    BugSleeperB Offline
    BugSleeper
    wrote on last edited by
    #1

    I Wrote a program follow the example (here), and want to study QtGraphs. If QtGraphs will replace QtCharts in future , some efferts are better to be done today.

    The problem is just the same,

    1. How to set different colors for each QLineSeries.
    2. How to remove extra lines links the end point of Line n and the first point of Line n+1.

    Thanks!

    Screen Shot

    20250727_202559-0-12.gif

    Codes:

    1. pro file

    QT       += core gui widgets quickwidgets graphs quick
    
    CONFIG += c++17
    SOURCES += \
        main.cpp \
        graphstest.cpp
    
    HEADERS += \
        graphstest.h
    
    FORMS += \
        graphstest.ui
    
    

    2. main.cpp

    #include "graphstest.h"
    
    #include <QApplication>
    
    int main(int argc, char *argv[])
    {
    	QApplication a(argc, argv);
    	graphsTest w;
    	w.show();
    	return a.exec();
    }
    
    

    3. graphstest.h

    #ifndef GRAPHSTEST_H
    #define GRAPHSTEST_H
    
    #include <QDateTimeAxis>
    #include <QDialog>
    #include <QLineSeries>
    #include <QValueAxis>
    #include <QVector>
    QT_BEGIN_NAMESPACE
    namespace Ui
    {
    
    class graphsTest;
    
    }
    QT_END_NAMESPACE
    
    class graphsTest : public QDialog
    {
    	Q_OBJECT
    
    public:
    	graphsTest(QWidget *parent = nullptr);
    	~graphsTest();
    
    protected:
    	void timerEvent(QTimerEvent *evt) override;
    private slots:
    	void on_pushButton_add_clicked();
    	void on_checkBox_update_clicked();
    
    private:
    	Ui::graphsTest *ui;
    	QDateTimeAxis *m_ax;
    	QValueAxis *m_ay;
    	int m_timerEvent;
    	QVector<QLineSeries *> m_lineSeries;
    };
    #endif // GRAPHSTEST_H
    
    

    4. graphstest.cpp

    #include "graphstest.h"
    #include <QDateTime>
    #include <QDebug>
    #include <QQuickItem>
    #include "ui_graphstest.h"
    graphsTest::graphsTest(QWidget *parent)
    	: QDialog(parent)
    	, ui(new Ui::graphsTest)
    	, m_ax(new QDateTimeAxis(this))
    	, m_ay(new QValueAxis(this))
    	, m_timerEvent(-1)
    {
    	ui->setupUi(this);
    	QDateTime dtmNow = QDateTime::currentDateTime();
    	m_ax->setMin(dtmNow.addDays(-1));
    	m_ax->setMax(dtmNow);
    	m_ax->setLabelFormat("yyyy\nMM-dd\nHH");
    	m_ay->setRange(-100, 100);
    
    	QList<QObject *> seriesList;
    	ui->graphsView->setResizeMode(QQuickWidget::SizeRootObjectToView);
    	ui->graphsView->setInitialProperties({{"seriesList", QVariant::fromValue(seriesList)},
    										  {"axisX", QVariant::fromValue(m_ax)},
    										  {"axisY", QVariant::fromValue(m_ay)},
    										  {"zoomAreaEnabled", true}});
    	ui->graphsView->loadFromModule("QtGraphs", "GraphsView");
    }
    
    graphsTest::~graphsTest()
    {
    	delete ui;
    }
    
    void graphsTest::timerEvent(QTimerEvent *evt)
    {
    	if (evt->timerId() == m_timerEvent)
    	{
    		QList<QPointF> data;
    		QDateTime dtmNow = QDateTime::currentDateTime();
    		const int N = m_lineSeries.size();
    		for (int n = 0; n < N; ++n)
    		{
    			for (int i = 0; i < 30; ++i)
    			{
    				data << QPointF(dtmNow.addSecs(-3600 * 24.0 / 30 * (29 - i)).toMSecsSinceEpoch(),
    								(rand() % 500 - 250) / 100.0 + n * 16 - 80);
    			}
    			m_lineSeries[n]->replace(data);
    		}
    		m_ax->setMin(dtmNow.addDays(-1));
    		m_ax->setMax(dtmNow);
    		if (!ui->checkBox_update->isChecked())
    		{
    			killTimer(m_timerEvent);
    			m_timerEvent = -1;
    		}
    	}
    	QDialog::timerEvent(evt);
    }
    
    void graphsTest::on_pushButton_add_clicked()
    {
    	if (m_lineSeries.size() >= 10)
    		return;
    	//Add to Graph
    	QVariant seriesListVariant = ui->graphsView->rootObject()->property("seriesList");
    	if (seriesListVariant.canConvert<QQmlListProperty<QObject>>())
    	{
    		QLineSeries *newLine = new QLineSeries(this);
    		newLine->setColor(QColor(rand() % 128, rand() % 128, rand() % 128));
    		newLine->setHoverable(true);
    		newLine->setName(QString("Testing %1").arg(m_lineSeries.size()));
    		connect(newLine,
    				&QAbstractSeries::hover,
    				[this](const QString &seriesName, QPointF position, QPointF value) -> void {
    					ui->lineEdit_msg->setText(QString("%1:%2 %3 = %4 %5")
    												  .arg(seriesName)
    												  .arg(position.x())
    												  .arg(position.y())
    												  .arg(value.x())
    												  .arg(value.y()));
    				});
    		//Add
    		QQmlListProperty<QObject> prop = seriesListVariant.value<QQmlListProperty<QObject>>();
    		prop.append(&prop, newLine);
    		m_lineSeries.append(newLine);
    		int cnt = prop.count(&prop);
    		qDebug() << cnt;
    	}
    	if (m_timerEvent < 0)
    		m_timerEvent = startTimer(500);
    }
    
    void graphsTest::on_checkBox_update_clicked()
    {
    	if (ui->checkBox_update->isChecked())
    		m_timerEvent = startTimer(500);
    }
    
    

    5. graphstest.ui

    <?xml version="1.0" encoding="UTF-8"?>
    <ui version="4.0">
     <class>graphsTest</class>
     <widget class="QDialog" name="graphsTest">
      <property name="geometry">
       <rect>
        <x>0</x>
        <y>0</y>
        <width>579</width>
        <height>332</height>
       </rect>
      </property>
      <property name="windowTitle">
       <string>graphsTest</string>
      </property>
      <layout class="QVBoxLayout" name="verticalLayout_2">
       <item>
        <layout class="QHBoxLayout" name="horizontalLayout">
         <item>
          <widget class="QQuickWidget" name="graphsView">
           <property name="resizeMode">
            <enum>QQuickWidget::ResizeMode::SizeRootObjectToView</enum>
           </property>
          </widget>
         </item>
         <item>
          <layout class="QVBoxLayout" name="verticalLayout">
           <property name="sizeConstraint">
            <enum>QLayout::SizeConstraint::SetMaximumSize</enum>
           </property>
           <item>
            <widget class="QPushButton" name="pushButton_add">
             <property name="sizePolicy">
              <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
               <horstretch>0</horstretch>
               <verstretch>0</verstretch>
              </sizepolicy>
             </property>
             <property name="text">
              <string>Add Serials</string>
             </property>
            </widget>
           </item>
           <item>
            <widget class="QCheckBox" name="checkBox_update">
             <property name="sizePolicy">
              <sizepolicy hsizetype="Maximum" vsizetype="Fixed">
               <horstretch>0</horstretch>
               <verstretch>0</verstretch>
              </sizepolicy>
             </property>
             <property name="text">
              <string>Updating</string>
             </property>
            </widget>
           </item>
           <item>
            <spacer name="verticalSpacer">
             <property name="sizePolicy">
              <sizepolicy hsizetype="Fixed" vsizetype="Expanding">
               <horstretch>0</horstretch>
               <verstretch>0</verstretch>
              </sizepolicy>
             </property>
             <property name="orientation">
              <enum>Qt::Orientation::Vertical</enum>
             </property>
             <property name="sizeHint" stdset="0">
              <size>
               <width>20</width>
               <height>40</height>
              </size>
             </property>
            </spacer>
           </item>
          </layout>
         </item>
        </layout>
       </item>
       <item>
        <widget class="QLineEdit" name="lineEdit_msg">
         <property name="sizePolicy">
          <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
           <horstretch>0</horstretch>
           <verstretch>0</verstretch>
          </sizepolicy>
         </property>
        </widget>
       </item>
      </layout>
     </widget>
     <customwidgets>
      <customwidget>
       <class>QQuickWidget</class>
       <extends>QWidget</extends>
       <header location="global">QtQuickWidgets/QQuickWidget</header>
      </customwidget>
     </customwidgets>
     <resources/>
     <connections/>
    </ui>
    
    
    1 Reply Last reply
    0
    • BugSleeperB Offline
      BugSleeperB Offline
      BugSleeper
      wrote on last edited by BugSleeper
      #2

      It's my falut. I have mentioned the author of the raw code , too.
      图片.png

      QList<QPointF> data should be cleared at each time.

      1 Reply Last reply
      1
      • BugSleeperB BugSleeper has marked this topic as solved on

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved