首页 > 解决方案 > Qt BarModelMapper 中的千位分隔符

问题描述

我想在表格和图表中添加千位分隔符。

在图表中。我找到了setLabelsFormat函数,但它不起作用。

series.setLabelsFormat('{0:,}')

在表中。我试试

def data(self, index, role=Qt.DisplayRole):
        if role == Qt.DisplayRole:
            return '{0:,}'.format(self.input_data[index.row()][index.column()])

看起来不错,但我的条形图消失了。pic BarChart 消失了:
pic 条形图消失了

画出我想要的:

图片:
图片

我的代码:

import sys
from random import randint

from PySide2.QtCore import QAbstractTableModel, QModelIndex, QRect, Qt
from PySide2.QtGui import QColor, QPainter
from PySide2.QtWidgets import (QApplication, QGridLayout, QHeaderView,
    QTableView, QWidget)
from PySide2.QtCharts import QtCharts

class CustomTableModel(QAbstractTableModel):
    def __init__(self):
        QAbstractTableModel.__init__(self)
        self.input_data = []
        self.mapping = {}
        self.columns = ['2020', '2021']
        self.rows = ['A', 'B', 'C', 'D']

        # create test data
        for i in range(len(self.rows)):
            data_vec = [0]*len(self.columns)
            for k in range(len(data_vec)):
                data_vec[k] = randint(0, 500) * randint(500, 1000) * 100
            self.input_data.append(data_vec)

    def rowCount(self, parent=QModelIndex()):
        return len(self.input_data)

    def columnCount(self, parent=QModelIndex()):
        return len(self.columns)

    def headerData(self, section, orientation, role):
        if role != Qt.DisplayRole:
            return None

        if orientation == Qt.Horizontal:
            return self.columns[section].title()
        else:
            return self.rows[section].title()

    def data(self, index, role=Qt.DisplayRole):
        if role == Qt.DisplayRole:
            return self.input_data[index.row()][index.column()]
        elif role == Qt.EditRole:
            return self.input_data[index.row()][index.column()]
        elif role == Qt.BackgroundRole:
            for color, rect in self.mapping.items():
                if rect.contains(index.column(), index.row()):
                    return QColor(color)
            # cell not mapped return white color
            return QColor(Qt.white)
        return None

    def setData(self, index, value, role=Qt.EditRole):
        if index.isValid() and role == Qt.EditRole:
            self.input_data[index.row()][index.column()] = float(value)
            self.dataChanged.emit(index, index)
            return True
        return False

    def flags(self, index):
        return Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable

    def add_mapping(self, color, area):
        self.mapping[color] = area

    def clear_mapping(self):
        self.mapping = {}

class TableWidget(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        self.model = CustomTableModel()

        self.table_view = QTableView()
        self.table_view.setModel(self.model)
        self.table_view.setMinimumWidth(500)
        self.table_view.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table_view.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)

        self.chart = QtCharts.QChart()
        self.chart.setAnimationOptions(QtCharts.QChart.AllAnimations)


        self.series = QtCharts.QBarSeries()
        self.series.setLabelsVisible(True)
        #self.series.setLabelsFormat('{0:,}')
        self.series.setLabelsPosition(QtCharts.QAbstractBarSeries.LabelsOutsideEnd)
        self.mapper = QtCharts.QVBarModelMapper(self)
        self.mapper.setFirstBarSetColumn(0)
        self.mapper.setLastBarSetColumn(2)
        self.mapper.setFirstRow(0)
        self.mapper.setRowCount(4)
        self.mapper.setSeries(self.series)
        self.mapper.setModel(self.model)
        self.chart.addSeries(self.series)

        # for storing color hex from the series
        seriesColorHex = "#000000"

        # get the color of the series and use it for showing the mapped area
        barsets = self.series.barSets()
        for i in range(len(barsets)):
            barsets[i].setLabelColor(Qt.black)
            seriesColorHex = "{}".format(barsets[i].brush().color().name())
            self.model.add_mapping(seriesColorHex, QRect(i, 0, 1, barsets[i].count()))
        
        
        self.chart_view = QtCharts.QChartView(self.chart)
        self.chart_view.setRenderHint(QPainter.Antialiasing)
        self.chart_view.setMinimumSize(640, 480)

        categories = ['A', 'B', 'C', 'D']
        axisX = QtCharts.QBarCategoryAxis()
        axisX.append(categories)
        self.chart.addAxis(axisX, Qt.AlignBottom)
        self.series.attachAxis(axisX)
        
        axisY = QtCharts.QValueAxis()
        self.chart.addAxis(axisY, Qt.AlignLeft)
        self.series.attachAxis(axisY)

        # create main layout
        self.main_layout = QGridLayout()
        self.main_layout.addWidget(self.table_view, 1, 0)
        self.main_layout.addWidget(self.chart_view, 1, 1)
        self.main_layout.setColumnStretch(1, 1)
        self.main_layout.setColumnStretch(0, 0)
        self.setLayout(self.main_layout)

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

标签: pythonpyside2qtcharts

解决方案


推荐阅读