提问人:Mika 提问时间:8/23/2023 更新时间:8/23/2023 访问量:41
QChart 填充太大,导致图表压缩
QChart padding is too big which causes charts compression
问:
我创建了一些图表并用它们填充主窗口。
最主要的是我无法减少内部(白色)填充,这会导致图表压缩和 Y 轴值消失。QChart
下面是作为最小可重现示例的代码:
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())
我已经找到了如何设置红色和黄色区域。但是无法弄清楚哪个小部件可以处理白色区域......
答:
0赞
Marco F.
8/23/2023
#1
在图表上额外使用 setMargin
chart->setMargins()
评论
1赞
Mika
8/23/2023
这很完美。但是,还需要 chart.layout().setContentsMargins(0, 0, 0, 0) 来删除外部边距。
评论
self.layout().setContentsMargins(10, 10, 10, 10)
chart->setMargins()