BarChartDataModel Example

import sys, os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../shared")

from DevMachines import __pyside2__, __pyside6__
from DevMachines.QtitanBase import Qtitan
from DevMachines.QtitanChart import (Chart, ChartBarSeries2D)

if __pyside2__:
    from PySide2 import QtCore
    from PySide2.QtCore import Qt
    from PySide2.QtGui import QBrush, QIcon
    from PySide2.QtWidgets import (QApplication, QComboBox, QHeaderView,
        QTableWidget, QTableWidgetItem, QTableWidgetSelectionRange, QToolBar, QAbstractItemView)

if __pyside6__:
    from PySide6 import QtCore
    from PySide6.QtCore import Qt
    from PySide6.QtGui import QBrush, QIcon
    from PySide6.QtWidgets import (QApplication, QComboBox, QHeaderView,
        QTableWidget, QTableWidgetItem, QTableWidgetSelectionRange, QToolBar, QAbstractItemView)

import BarChartDataModel_rc

from DemoChartWindow import DemoChartWindow

class MainWindow(DemoChartWindow):
    SelectionDataModel = 0
    EditDataModel = 1
    def __init__(self):
        DemoChartWindow.__init__(self, "Spline Chart with Model")
        self.columnCount = 3
        self.rowCount = 12
        self.orientation = Qt.Vertical

        self.setChart(self.createChart(), self.createDataBindingWidget())
        self.createSeriesParametrs()
        self.seriesChanged(self.seriesSwitcher.currentIndex())

    def createChart(self):
        return Chart(self)

    def createDataBindingWidget(self):
        self.tableWidget = QTableWidget(self)
        self.tableWidget.setMaximumWidth(250)
        self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        return self.tableWidget

    def createSeriesParametrs(self):
        dataBindingGroup = self.createGroupParameters(self.tr("Data Binding"))
        formLayout = dataBindingGroup.layout()
        self.seriesSwitcher = QComboBox(dataBindingGroup)
        self.seriesSwitcher.addItem("Selection Model", MainWindow.SelectionDataModel)
        self.seriesSwitcher.addItem("Edit Model", MainWindow.EditDataModel)
        self.connect(self.seriesSwitcher, QtCore.SIGNAL("currentIndexChanged(int)"), self,
            QtCore.SLOT("seriesChanged(int)"))
        formLayout.addRow(self.seriesSwitcher)
        self.toolBar = QToolBar(self)
        self.actAppendRow = self.toolBar.addAction(QIcon(":\\shared\\res\\appendrow.png"), self.tr("Append Row"))
        self.actAppendRow.setEnabled(False)
        self.connect(self.actAppendRow, QtCore.SIGNAL("triggered()"), self, QtCore.SLOT("appendRow()"))
        self.actDeleteRow = self.toolBar.addAction(QIcon(":\\shared\\res\\deleterow.png"), self.tr("Delete Row"))
        self.actDeleteRow.setEnabled(False)
        self.connect(self.actDeleteRow, QtCore.SIGNAL("triggered()"), self, QtCore.SLOT("deleteRow()"))
        formLayout.addRow(self.toolBar)

    def createSelectionModelSeries(self):
        self.disconnect(self.tableWidget, QtCore.SIGNAL("itemSelectionChanged()"), self, QtCore.SLOT("updateEnableButtons()"))
        self.connect(self.tableWidget, QtCore.SIGNAL("itemSelectionChanged()"), self, QtCore.SLOT("setSelectionData()"))

        self.createTitle(self.tr("Selection Data Model"))
        self.chart.legend().setVisible(True)

        series = ChartBarSeries2D()
        series.setName(self.tr("Input Series"))
        self.chart.appendSeries(series)

        view2D = self.chart.views()[0]
        axisX = view2D.axisX()
        axisX.label().setAngle(45)
        series.modelController().setModel(self.tableWidget.model())

    def createEditModelSeries(self):
        self.disconnect(self.tableWidget, QtCore.SIGNAL("itemSelectionChanged()"), self,
            QtCore.SLOT("setSelectionData()"))
        self.connect(self.tableWidget, QtCore.SIGNAL("itemSelectionChanged()"), self,
            QtCore.SLOT("updateEnableButtons()"))

        self.createTitle(self.tr("Edit Data Model"))
        self.chart.legend().setVisible(True)

        series = ChartBarSeries2D()
        series.setName(self.tr("Input Series"))
        self.chart.appendSeries(series)

        view2D = self.chart.views()[0]
        axisX = view2D.axisX()
        axisX.label().setAngle(45)
        series.modelController().setModel(self.tableWidget.model())

    def fillDataTable(self):
        self.tableWidget.clear()
        self.tableWidget.setColumnCount(self.columnCount)
        self.tableWidget.setRowCount(self.rowCount)

        for i in range(0, self.rowCount):
            for k in range(0, self.columnCount):
                item = QTableWidgetItem()
                value = 0
                if k == 0:
                    value = self.getRandomValue(10, 30)
                    item.setText("{}".format(value))
                    self.tableWidget.setItem(i, k, item)
                else:
                    item.setText("{} Precipitation".format(i + 1))
                    self.tableWidget.setItem(i, k, item)

    def initSelectionRange(self):
        self.tableWidget.clearSelection()
        _range = QTableWidgetSelectionRange(0, 0, self.rowCount-1, 1)
        self.tableWidget.setRangeSelected(_range, True)

    def updateValueParameters(self):
        DemoChartWindow.updateValueParameters(self)

    def seriesChanged(self, index):
        self.chart.clearSeries()
        self.chart.clearTitles()
        self.chart.setBackgroundBrush(QBrush())

        v = self.seriesSwitcher.itemData(index)
        if int(v) == MainWindow.SelectionDataModel:
            self.tableWidget.clearSelection()
            self.tableWidget.setSelectionMode(QAbstractItemView.ContiguousSelection)
            self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
            self.tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
            self.toolBar.hide()
            self.columnCount = 2
            self.rowCount = 12
            self.fillDataTable()
            self.createSelectionModelSeries()
            self.initSelectionRange()
        elif int(v) == MainWindow.EditDataModel:
            self.tableWidget.clearSelection()
            self.tableWidget.setSelectionMode(QAbstractItemView.SingleSelection)
            self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
            self.tableWidget.setEditTriggers(QAbstractItemView.AllEditTriggers)
            self.toolBar.show()
            self.columnCount = 2
            self.rowCount = 12
            self.fillDataTable()
            self.createEditModelSeries()

        self.updateValueParameters()

    @QtCore.Slot()
    def setSelectionData(self):
        if len(self.chart.series()) == 0:
            return

        series = self.chart.series()[0]

        if series.inherits("Qtitan::ChartBarSeries2D"):
            selectedRanges = self.tableWidget.selectedRanges()
            if len(selectedRanges) == 1:
                selected = selectedRanges[0]
                if selected.leftColumn() == selected.rightColumn():
                    series.modelController().setAxisXColumn(-1)
                else:
                    series.modelController().setAxisXColumn(selected.leftColumn())
                series.modelController().setAxisYColumn(selected.rightColumn())
                series.modelController().setRowRange(selected.topRow(), selected.bottomRow())
            else:
                series.modelController().setRowRange(-1, -1)

    def appendRow(self):
        if len(self.chart.series()) == 0:
            return
        numNewRow = 0
        selectedRanges = self.tableWidget.selectedRanges()
        if len(selectedRanges) > 0:
            indexEdit = self.tableWidget.currentIndex()
            if indexEdit.isValid():
                itemEdit = self.tableWidget.item(indexEdit.row(), indexEdit.column())
                if not itemEdit is None:
                    self.tableWidget.closePersistentEditor(itemEdit)

            self.tableWidget.reset()

            selected = selectedRanges[len(selectedRanges) - 1]
            numNewRow = selected.topRow() + 1

        self.rowCount = self.rowCount + 1

        self.tableWidget.insertRow(numNewRow)

        itemX = QTableWidgetItem()
        itemX.setText("1")
        self.tableWidget.setItem(numNewRow, 0, itemX)

        itemY = QTableWidgetItem()
        itemY.setText("Test")
        self.tableWidget.setItem(numNewRow, 1, itemY)

        _range = QTableWidgetSelectionRange(numNewRow, 0, numNewRow, self.columnCount - 1)
        self.tableWidget.setRangeSelected(_range, True)

        index = self.tableWidget.model().index(numNewRow, 0)
        if index.isValid():
            self.tableWidget.setCurrentIndex(index)
            self.tableWidget.edit(index)

        series = self.chart.series()[0]
        if series.inherits("Qtitan::ChartBarSeries2D"):
            series.modelController().setColumnRange(0, self.rowCount - 1)

    def deleteRow(self):
        if len(self.chart.series()) == 0:
            return

        selectedRanges = self.tableWidget.selectedRanges()
        for selected in selectedRanges:
            self.tableWidget.removeRow(selected.topRow())

            self.rowCount = self.rowCount - 1
            series = self.chart.series()[0]
            if series.inherits("Qtitan::ChartPointSeries"):
              controller = series.modelController()
              controller.setColumnRange(0, self.rowCount - 1)

        self.updateEnableButtons()

    @QtCore.Slot()
    def updateEnableButtons(self):
        if len(self.chart.series()) == 0:
            return

        if self.orientation == Qt.Horizontal:
            isEmpty = self.tableWidget.model().columnCount() == 0
        else:
            isEmpty = self.tableWidget.model().rowCount() == 0

        selectedRanges = self.tableWidget.selectedRanges()

        self.actDeleteRow.setEnabled(len(selectedRanges) > 0)
        self.actAppendRow.setEnabled(isEmpty or len(selectedRanges) > 0)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())