Search code examples
pythonpython-3.xqtchartspyqt

QChart padding is too big which causes charts compression


I create some charts and filling main window with them.

The main thing is that i can't decrease the inner (white colored) padding of the QChart and this causes charts compression and Y axis values disappearing.

Here is the code as a minimum reproducible example:

import sys
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget
from PySide6 import QtCharts, QtGui


import random


class Chart(QtCharts.QChart):
    def __init__(self):
        super().__init__()
        self.create_series()
        self.createDefaultAxes()

        self.legend().setVisible(True)
        self.legend().setAlignment(Qt.AlignLeft)
        self.layout().setContentsMargins(10, 10, 10, 10)

    def create_series(self, s=3):
        for j in range(s):
            series = QtCharts.QLineSeries()
            if j == 0:
                for i in range(150):
                    if i % 10 == 0:
                        series.append(i, random.randint(0, 10))
                    else:
                        series.append(i, 2)
                self.addSeries(series)


class ChartView(QtCharts.QChartView):
    def __init__(self, chart):
        super().__init__()

        self.setChart(chart)
        self.setRenderHint(QtGui.QPainter.Antialiasing)
        self.setRubberBand(QtCharts.QChartView.RectangleRubberBand)
        self.setStyleSheet("background-color: yellow;")



class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.central_widget = QWidget()
        self.central_widget.setObjectName('central_widget')
        self.layout = QVBoxLayout(self.central_widget)
        self.layout.setSpacing(0)
        self.layout.setContentsMargins(20, 20, 20, 20)

        for _ in range(6):
            chart_view = self.create_chart_view()
            self.layout.addWidget(chart_view)

        self.setStyleSheet('#central_widget{background: red}')
        self.setCentralWidget(self.central_widget)

    def create_chart_view(self):
        chart = Chart()
        chart_view = ChartView(chart=chart)
        return chart_view


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

I've found how to setup red and yellow areas. But can't figure out which widget can handle white area...


Solution

  • Use additionally setMargin on your chart

    chart->setMargins()