pythonuser-interfacepyqtqcustomplot

QCustomPlot python: How do I set fill color of a plot item?


I'm trying to add an QItemEllipse to my plot.

In the docs it says you can set the line style/color/width by creating a QPen and the fill color/style

from PySide2.QtGui import QBrush, QPen, Qt
from PySide2.QtWidgets import QApplication, QWidget, QVBoxLayout

import sys

from qcustomplot_pyside2 import QCPItemEllipse, QCustomPlot

app = QApplication(sys.argv)

window = QWidget()
window.setFixedSize(500, 500)
window.setLayout(QVBoxLayout())

qcustomplot = QCustomPlot()
window.layout().addWidget(qcustomplot)


ellipse = QCPItemEllipse(qcustomplot)
ellipse.bottomRight.setCoords(-2, -2)
ellipse.topLeft.setCoords(2, 2)
pen = QPen()
brush = QBrush()
brush.setColor(Qt.cyan)
pen.setBrush(brush)
pen.setColor(Qt.magenta)

ellipse.setPen(pen)

qcustomplot.replot()
qcustomplot.update()
qcustomplot.updateGeometry()
window.update()
window.show()
app.exec_()

There is still no fill color, have I missed something?


Solution

  • You should use the QCPItemEllipse.setBrush(), and set the brush style to Qt.SolidPattern. So, do like this.

    ...
    brush = QBrush()
    brush.setColor(Qt.cyan)
    brush.setStyle(Qt.SolidPattern)
    #pen.setBrush(brush) # This is wrong!
    ellipse.setBrush(brush)
    ...
    

    And you can create a solid brush more easily by using the constructor like this.

    ellipse.setBrush(QBrush(Qt.cyan))