logo
down
shadow

How to add qml ScatterSeries to existing qml defined ChartView?


How to add qml ScatterSeries to existing qml defined ChartView?

Content Index :

How to add qml ScatterSeries to existing qml defined ChartView?
Tag : python , By : mgaspar
Date : January 12 2021, 09:11 PM

should help you out The QML Charts API is written based on the API used by C++ but it is not the same, for example the ChartView is a QQuickItem that does not expose the QChart unlike QChartView is a QGraphicsView(QWidget) that if it exposes the QChart, what Same is with the series. In conclusion you will not be able to use C++(Python) classes to interact with QML.
The example you show at the beginning is not an example for C++ but for QML so it cannot be translated directly into QML. It is also not possible to create a QML Series in C++/Python with QtCharts classes directly, a possible strategy is to use QQmlExpression that can evaluate QML elements and return it to C++/Python. In addition, the createSeries() method not only adds the series but also connects signals.
from enum import Enum, auto
from PySide2 import QtCore, QtGui, QtWidgets, QtQml

# https://code.qt.io/cgit/qt/qtcharts.git/tree/src/chartsqml2/declarativechart_p.h#n105
class SeriesType(Enum):
    SeriesTypeLine = 0
    SeriesTypeArea = auto()
    SeriesTypeBar = auto()
    SeriesTypeStackedBar = auto()
    SeriesTypePercentBar = auto()
    SeriesTypePie = auto()
    SeriesTypeScatter = auto()
    SeriesTypeSpline = auto()
    SeriesTypeHorizontalBar = auto()
    SeriesTypeHorizontalStackedBar = auto()
    SeriesTypeHorizontalPercentBar = auto()
    SeriesTypeBoxPlot = auto()
    SeriesTypeCandlestick = auto()


class DataModel(QtCore.QObject):
    def __init__(self, engine, parent=None):
        super().__init__(parent)
        self.m_engine = engine

    @QtCore.Slot(QtCore.QObject, QtCore.QObject, QtCore.QObject, result=QtCore.QObject)
    def addChartSeries(self, chart_view, chart_axis_x, chart_axis_y):
        context = QtQml.QQmlContext(self.m_engine.rootContext())
        context.setContextProperty("chart_view", chart_view)
        context.setContextProperty("axis_x", chart_axis_x)
        context.setContextProperty("axis_y", chart_axis_y)
        context.setContextProperty("type", SeriesType.SeriesTypeScatter.value)
        script = """chart_view.createSeries(type, "scatter series", axis_x, axis_y);"""
        expression = QtQml.QQmlExpression(context, chart_view, script)
        serie, valueIsUndefined = expression.evaluate()
        if expression.hasError():
            print(expression.error())
            return

        import random

        mx, Mx = chart_axis_x.property("min"), chart_axis_x.property("max")
        my, My = chart_axis_y.property("min"), chart_axis_y.property("max")
        if not valueIsUndefined:
            for _ in range(100):
                x = random.uniform(mx, Mx)
                y = random.uniform(my, My)
                serie.append(x, y)
            # https://doc.qt.io/qt-5/qml-qtcharts-scatterseries.html#borderColor-prop
            serie.setProperty("borderColor", QtGui.QColor("salmon"))
            # https://doc.qt.io/qt-5/qml-qtcharts-scatterseries.html#brush-prop
            serie.setProperty("brush", QtGui.QBrush(QtGui.QColor("green")))
            # https://doc.qt.io/qt-5/qml-qtcharts-scatterseries.html#borderColor-prop
            serie.setProperty("borderWidth", 4.0)
            return serie


if __name__ == "__main__":
    import os
    import sys

    current_dir = os.path.dirname(os.path.realpath(__file__))

    app = QtWidgets.QApplication(sys.argv)
    engine = QtQml.QQmlApplicationEngine()

    dataModel = DataModel(engine)

    engine.rootContext().setContextProperty("dataModel", dataModel)
    file = os.path.join(current_dir, "main.qml")
    engine.load(QtCore.QUrl.fromLocalFile(file))
    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())
import QtQuick 2.12
import QtQuick.Controls 2.12
import QtCharts 2.2


ApplicationWindow {
    visible: true
    width: 640
    height: 480

    ChartView {
        anchors.fill: parent
        id: bscan0
        ValueAxis {
            id: bscan0_xAxix
            min: 0
            max: 10
        }

        ValueAxis {
            id: bscan0_yAxis
            min: -100
            max: 100
        }
        Component.onCompleted: {
            var serie = dataModel.addChartSeries(bscan0, bscan0_xAxix, bscan0_yAxis)
        }
    }
}
import random
from PySide2 import QtCore, QtGui, QtWidgets, QtQml, QtCharts


class DataModel(QtCore.QObject):
    @QtCore.Slot(QtCharts.QtCharts.QAbstractSeries)
    def fill_serie(self, serie):
        mx, Mx = 0, 10
        my, My = -100, 100
        for _ in range(100):
            x = random.uniform(mx, Mx)
            y = random.uniform(my, My)
            serie.append(x, y)
        # https://doc.qt.io/qt-5/qml-qtcharts-scatterseries.html#borderColor-prop
        serie.setProperty("borderColor", QtGui.QColor("salmon"))
        # https://doc.qt.io/qt-5/qml-qtcharts-scatterseries.html#brush-prop
        serie.setProperty("brush", QtGui.QBrush(QtGui.QColor("green")))
        # https://doc.qt.io/qt-5/qml-qtcharts-scatterseries.html#borderColor-prop
        serie.setProperty("borderWidth", 4.0)


if __name__ == "__main__":
    import os
    import sys

    current_dir = os.path.dirname(os.path.realpath(__file__))

    app = QtWidgets.QApplication(sys.argv)
    engine = QtQml.QQmlApplicationEngine()

    dataModel = DataModel(engine)

    engine.rootContext().setContextProperty("dataModel", dataModel)
    file = os.path.join(current_dir, "main.qml")
    engine.load(QtCore.QUrl.fromLocalFile(file))
    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())
import QtQuick 2.12
import QtQuick.Controls 2.12
import QtCharts 2.2


ApplicationWindow {
    visible: true
    width: 640
    height: 480

    ChartView {
        anchors.fill: parent
        id: bscan0
        ValueAxis {
            id: bscan0_xAxix
            min: 0
            max: 10
        }

        ValueAxis {
            id: bscan0_yAxis
            min: -100
            max: 100
        }
        Component.onCompleted: {
            var serie = bscan0.createSeries(ChartView.SeriesTypeScatter, "scatter series", bscan0_xAxix, bscan0_yAxis);
            dataModel.fill_serie(serie)
        }
    }
}

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

WPF Binding Telerik Chartview


Tag : chash , By : Chris Hanley
Date : March 29 2020, 07:55 AM
wish of those help I suggest you go and read some documentation.
Here is a good link to Telerik's RadCartesianChart using BarSeries.
<telerik:RadCartesianChart Palette="Windows8">
<telerik:RadCartesianChart.HorizontalAxis>
    <telerik:CategoricalAxis/>
</telerik:RadCartesianChart.HorizontalAxis>
<telerik:RadCartesianChart.VerticalAxis>
    <telerik:LinearAxis />
</telerik:RadCartesianChart.VerticalAxis>
<telerik:RadCartesianChart.Series>
    <telerik:BarSeries>
        <telerik:BarSeries.DataPoints>
            <telerik:CategoricalDataPoint Category="January" Value="2" />
            <telerik:CategoricalDataPoint Category="February" Value="5" />
            <telerik:CategoricalDataPoint Category="March" Value="3" />
            <telerik:CategoricalDataPoint Category="April" Value="10" />
            <telerik:CategoricalDataPoint Category="May" Value="9" />
            <telerik:CategoricalDataPoint Category="June" Value="7" />
            <telerik:CategoricalDataPoint Category="July" Value="1" />
        </telerik:BarSeries.DataPoints>
    </telerik:BarSeries>
</telerik:RadCartesianChart.Series>
</telerik:RadCartesianChart>

Custom Tooltip in WPF Charting ScatterSeries


Tag : wpf , By : Doc Immortal
Date : March 29 2020, 07:55 AM
hope this fix your issue I think this question has the answer you are looking for WPF toolkit charting : Customize datapoint label
Basically you want to add more entries to your ToolTipService.ToolTip declaration
<ToolTipService.ToolTip>
    <StackPanel>
        <ContentControl
          Content="Custom ToolTip"
          FontWeight="Bold"/>
        <ContentControl
          Content="{TemplateBinding Key}"/><!--I am not sure what the correct property will be Key is a guess-->
        <ContentControl
          Content="{TemplateBinding IndependentValue}"/>
        <ContentControl
          Content="{TemplateBinding DependentValue}"/>
    </StackPanel>
</ToolTipService.ToolTip>

ShinobiChart Multiple Point Selection in ScatterSeries


Tag : ios , By : Joe
Date : March 29 2020, 07:55 AM
may help you . I think what you're looking for is series.togglePointSelection = YES. This will allow the series' points to have their selection toggled, instead of only one being set at a time.
Hope this helps!

How to add a rectangle to a QML ChartView?


Tag : qt , By : KS9
Date : December 25 2020, 09:19 AM
Hope this helps To translate from the ScatterSeries coordinate system to pixel coordinates to place a child in ChartView use mapToPosition(...):
function updateRectangle() {
    var topLeftPoint = view.mapToPosition(Qt.point(30,60), series)
    var bottomRightPoint = view.mapToPosition(Qt.point(70,50), series)

    rec.x = topLeftPoint.x
    rec.y = topLeftPoint.y

    rec.width  = bottomRightPoint.x - topLeftPoint.x
    rec.height = bottomRightPoint.y - topLeftPoint.y
}

Add c++ QAbstractSeries to QML chartview


Tag : cpp , By : DotNetWise
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • Python can't import function
  • Pieces doesn't stack after one loop on my connect4
  • How to change font size of all .docx document with python-docx
  • How to store a word with # in .cfg file
  • How to append dictionaries to a dictionary?
  • How can I scrape text within paragraph tag with some other tags then within the paragraph text?
  • Custom entity ruler with SpaCy did not return a match
  • Logging with two handlers - one to file and one to stderr
  • How to do pivot_table in dask with aggfunc 'min'?
  • This for loop displays only the last entry of the student record
  • How to split a string by a specific pattern in number of characters?
  • Python 3: how to scrape research results from a website using CSFR?
  • Setting the scoring parameter of RandomizedSeachCV to r2
  • How to send alert or message from view.py to template?
  • Django + tox: Apps aren't loaded yet
  • My css and images arent showing in django
  • Probability mass function sum 2 dice roll?
  • Cannot call ubuntu 'ulimit' from python subprocess without using shell option
  • Dataframe Timestamp Filter for new/repeating value
  • Problem with clicking select2 dropdownlist in selenium
  • pandas dataframe masks to write values into new column
  • How to click on item in navigation bar on top of page using selenium python?
  • Add multiple EntityRuler with spaCy (ValueError: 'entity_ruler' already exists in pipeline)
  • error when replacing missing ')' using negative look ahead regex in python
  • Is there a way to remove specific strings from indexes using a for loop?
  • select multiple tags by position in beautifulSoup
  • pytest: getting AttributeError: 'CaptureFixture' object has no attribute 'readouterror' capturing stdout
  • Shipping PyGObject/GTK+ app on Windows with MingW
  • Python script to deduplicate lines in multiple files
  • How to prevent window and widgets in a pyqt5 application from changing size when the visibility of one widget is altered
  • How to draw stacked bar plot from df.groupby('feature')['label'].value_counts()
  • Python subprocess doesn't work without sleep
  • How can I adjust 'the time' in python with module Re
  • Join original np array with resulting np array in a form of dictionary? multidimensional array? etc?
  • Forcing labels on histograms in each individual graph in a figure
  • For an infinite dataset, is the data used in each epoch the same?
  • Is there a more efficent way to extend a string?
  • How to calculate each single element of a numpy array based on conditions
  • How do I change the width of Jupyter notebook's cell's left part?
  • Measure distance between lat/lon coordinates and utm coordinates
  • Installing megam for NLTK on Windows
  • filter dataframe on each value of a samn column have a specific value of another column in Panda\Python
  • Threading with pubsub throwing AssertionError: 'callableObj is not callable' in wxPython
  • Get grouped data from 2 dataframes with condition
  • How can I import all of sklearns regressors
  • How to take all elements except the first k
  • Whats wrong with my iteration list of lists from csv
  • Tensorflow Estimator API save image summary in eval mode
  • How to Pack with PyQt - how to make QFrame/Layout adapt to content
  • How do I get certain Time Range in Python
  • python doubly linked list - insertAfter node
  • Open .h5 file in Python
  • Joining a directory name with a binary file name
  • python, sort list with two arguments in compare function
  • Is it possible to print from Python using non-ANSI colors?
  • Pandas concat historical data using date minus some number of days
  • CV2: Import Error in Python OpenCV
  • Is it possible to do this loop in a one-liner?
  • invalid literal for int() with base 10: - django
  • Why does my code print a value that I have not assigned as yet?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com