Search code examples
pythonpyqtpyqt5qchart

QValueAxis show messy code (chinese language)?


in my chart the x axis need to show chinese and y axis need to show english, but x axis show messy code. can any one help me?

self.chart.createDefaultAxes()
axis_x, axis_y = self.chart.axes()
axis_x.setLabelFormat('%.2f分')
axis_y.setLabelFormat('%dmA')

it look like this: enter image description here


Solution

  • It seems that there is incompatibility between the encoders that QString uses in QtCharts and str (even finding out the reason for the problem), but I have managed to implement a solution that does the conversion:

    import random
    from PyQt5 import QtCore, QtWidgets, QtChart
    
    
    def convert(word):
        return "".join(chr(e) for e in word.encode())
    
    
    class MainWindow(QtWidgets.QMainWindow):
        def __init__(self, parent=None):
            super(MainWindow, self).__init__(parent)
    
            series = QtChart.QLineSeries(name="random serie")
    
            for i in range(20):
                series << QtCore.QPointF(0.1 * i, random.uniform(-10, 10))
    
            self.chart = QtChart.QChart()
            self.chart.setTitle("Title")
            self.chart.addSeries(series)
            self.chart.createDefaultAxes()
            axis_x, axis_y = self.chart.axes()
            axis_x.setLabelFormat(convert("%.2f分"))
            axis_y.setLabelFormat("%dmA")
    
            view = QtChart.QChartView(self.chart)
            self.setCentralWidget(view)
    
    
    if __name__ == "__main__":
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
    
        w = MainWindow()
        w.resize(640, 240)
        w.show()
        sys.exit(app.exec_())
    

    enter image description here