Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Graphs don't have the values after turning them into images

Graphs don't have the values after turning them into images

Scheduled Pinned Locked Moved Unsolved General and Desktop
2 Posts 2 Posters 238 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • R Offline
    R Offline
    Rangerguy128
    wrote on last edited by
    #1

    This has been a real headscratcher for a while. I’ve been working to intergrate a print function for my desktop app program where the users can print a document with the generated graphs added on it. Before I do that, I need to find a way to save the graphs as images. After many attempts, I only managed to print out images of the graphs before the data was to be added, even though I saved these images right after adding the values from a CSV file into the graph. This is what it should look like:
    35b371e9-9408-4294-9e28-114aa85f481e-image.png
    However, when I try to save the image, it just shows the graphs but without the values (the colored bars) Mind you, I'm using PyQt and CustomWidgets to create the graphs. Here's what I've used to create the graph in my code, as well as saving it as an image:

    def create_temp_chart(self):
            if not self.fileName:
                return
            low = QtChart.QBarSet("min")
            high = QtChart.QBarSet("max")
            ltemp = []
            htemp = []
    
            with open(self.fileName) as csvfile:
                csvreader = csv.reader(csvfile, delimiter=',')
                header_found = False
                for row in csvreader:
                    if row[0] == "MinTemp":
                        header_found = True
                        continue
                    if header_found:
                        ltemp.append(float(row[0]))
                        htemp.append(float(row[1]))
                    if len(ltemp) >= 12:
                        break  # Assuming only the first 12 months of data are needed
    
            low.append(ltemp)
            high.append(htemp)
    
            series = QtChart.QStackedBarSeries()
            series.append(low)
            series.append(high)
    
            chart = QtChart.QChart()
            chart.addSeries(series)
            chart.setTitle("Muestra de Temperatura en Celsius")
            chart.setAnimationOptions(QtChart.QChart.AnimationOption.SeriesAnimations)
    
            category = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    
            axisX = QtChart.QBarCategoryAxis()
            axisX.append(category)
            axisX.setTitleText("Mes")
            chart.addAxis(axisX, Qt.AlignmentFlag.AlignBottom)
            axisY = QtChart.QValueAxis()
            axisY.setRange(-52, 52)
            axisY.setTitleText("Temperatura en Celsius")
            chart.addAxis(axisY, Qt.AlignmentFlag.AlignLeft)
            series.attachAxis(axisX)
            series.attachAxis(axisY)
    
            self.ui.chart_view_temp = QtChart.QChartView(chart)
            self.ui.chart_view_temp.setRenderHint(QPainter.RenderHint.Antialiasing)
            self.ui.chart_view_temp.chart().setTheme(QtChart.QChart.ChartTheme.ChartThemeDark)
            sizePolicy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
            sizePolicy.setHeightForWidth(self.ui.chart_view_temp.sizePolicy().hasHeightForWidth())
            self.ui.chart_view_temp.setSizePolicy(sizePolicy)
    
            self.ui.gridLayout_2.addWidget(self.ui.chart_view_temp)
            self.ui.frame_18.setStyleSheet(u"background-color: transparent")
    
            # Save chart as image
            self.save_chart_as_image(self.ui.chart_view_temp, "temp_chart.png")
    
    def save_chart_as_image(self, chart_view, file_name):
            QApplication.processEvents()  # Process all pending events to ensure rendering is complete
    
            image = QImage(chart_view.size(), QImage.Format.Format_ARGB32)
            painter = QPainter(image)
            chart_view.render(painter)
            painter.end()
            image.save(file_name)
    
            # Display the image after saving
            self.display_image(file_name)
    
        def display_image(self, file_path):
            dialog = QDialog(self)
            dialog.setWindowTitle("Chart Image")
            layout = QVBoxLayout()
            label = QLabel()
            pixmap = QPixmap(file_path)
            label.setPixmap(pixmap)
            layout.addWidget(label)
            dialog.setLayout(layout)
            dialog.exec_()
    

    Any advice on how to fix this?

    JonBJ 1 Reply Last reply
    0
    • R Rangerguy128

      This has been a real headscratcher for a while. I’ve been working to intergrate a print function for my desktop app program where the users can print a document with the generated graphs added on it. Before I do that, I need to find a way to save the graphs as images. After many attempts, I only managed to print out images of the graphs before the data was to be added, even though I saved these images right after adding the values from a CSV file into the graph. This is what it should look like:
      35b371e9-9408-4294-9e28-114aa85f481e-image.png
      However, when I try to save the image, it just shows the graphs but without the values (the colored bars) Mind you, I'm using PyQt and CustomWidgets to create the graphs. Here's what I've used to create the graph in my code, as well as saving it as an image:

      def create_temp_chart(self):
              if not self.fileName:
                  return
              low = QtChart.QBarSet("min")
              high = QtChart.QBarSet("max")
              ltemp = []
              htemp = []
      
              with open(self.fileName) as csvfile:
                  csvreader = csv.reader(csvfile, delimiter=',')
                  header_found = False
                  for row in csvreader:
                      if row[0] == "MinTemp":
                          header_found = True
                          continue
                      if header_found:
                          ltemp.append(float(row[0]))
                          htemp.append(float(row[1]))
                      if len(ltemp) >= 12:
                          break  # Assuming only the first 12 months of data are needed
      
              low.append(ltemp)
              high.append(htemp)
      
              series = QtChart.QStackedBarSeries()
              series.append(low)
              series.append(high)
      
              chart = QtChart.QChart()
              chart.addSeries(series)
              chart.setTitle("Muestra de Temperatura en Celsius")
              chart.setAnimationOptions(QtChart.QChart.AnimationOption.SeriesAnimations)
      
              category = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
      
              axisX = QtChart.QBarCategoryAxis()
              axisX.append(category)
              axisX.setTitleText("Mes")
              chart.addAxis(axisX, Qt.AlignmentFlag.AlignBottom)
              axisY = QtChart.QValueAxis()
              axisY.setRange(-52, 52)
              axisY.setTitleText("Temperatura en Celsius")
              chart.addAxis(axisY, Qt.AlignmentFlag.AlignLeft)
              series.attachAxis(axisX)
              series.attachAxis(axisY)
      
              self.ui.chart_view_temp = QtChart.QChartView(chart)
              self.ui.chart_view_temp.setRenderHint(QPainter.RenderHint.Antialiasing)
              self.ui.chart_view_temp.chart().setTheme(QtChart.QChart.ChartTheme.ChartThemeDark)
              sizePolicy = QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
              sizePolicy.setHeightForWidth(self.ui.chart_view_temp.sizePolicy().hasHeightForWidth())
              self.ui.chart_view_temp.setSizePolicy(sizePolicy)
      
              self.ui.gridLayout_2.addWidget(self.ui.chart_view_temp)
              self.ui.frame_18.setStyleSheet(u"background-color: transparent")
      
              # Save chart as image
              self.save_chart_as_image(self.ui.chart_view_temp, "temp_chart.png")
      
      def save_chart_as_image(self, chart_view, file_name):
              QApplication.processEvents()  # Process all pending events to ensure rendering is complete
      
              image = QImage(chart_view.size(), QImage.Format.Format_ARGB32)
              painter = QPainter(image)
              chart_view.render(painter)
              painter.end()
              image.save(file_name)
      
              # Display the image after saving
              self.display_image(file_name)
      
          def display_image(self, file_path):
              dialog = QDialog(self)
              dialog.setWindowTitle("Chart Image")
              layout = QVBoxLayout()
              label = QLabel()
              pixmap = QPixmap(file_path)
              label.setPixmap(pixmap)
              layout.addWidget(label)
              dialog.setLayout(layout)
              dialog.exec_()
      

      Any advice on how to fix this?

      JonBJ Offline
      JonBJ Offline
      JonB
      wrote on last edited by JonB
      #2

      @Rangerguy128
      I know nothing about when QtCharts might or might not finishing rendering/showing, if that is required to get your saved image right, But

      QApplication.processEvents()  # Process all pending events to ensure rendering is complete
      

      This for sure is insufficient. Basically you "probably" have something wrong if you are calling processEvents().

      Start by changing so that you do not call save_chart_as_image() from within the code which has just created a chart. It's not shown/rendered at this point. Call it, say, from a slot attached to a singleshot timer, which gives enough time for the graph to render properly. If that works you can look at speeding up by maybe doing it from something like a showEvent() if you don't want to use a timer.

      1 Reply Last reply
      1

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved