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. Appending an image to itemList of QFormLayout widgets
Forum Updated to NodeBB v4.3 + New Features

Appending an image to itemList of QFormLayout widgets

Scheduled Pinned Locked Moved Unsolved General and Desktop
51 Posts 4 Posters 6.5k Views 3 Watching
  • 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.
  • C CEO.

    part of the sql data retrieval code:

                           result = self.cursor.fetchall()             
                         for row_number, row_data in enumerate(result):             
                             self.tab.insertRow(row_number)             
                             for column_number, data in enumerate(row_data):             
                                 self.tab.setItem(row_number, column_number, QTableWidgetItem(str(data)))
    

    part of the itemsArray code:

                                  for row in rows:                      
                                      for col in range(self.tab.columnCount()):                      
                                          itemArray = self.tab.item(row, col)
                    
                                        
    
                         
                       text = "" if itemArray is None else itemArray.text()                 
                    
                         if (col == 14):
                        itemList[12].setText(text)
                        imgcon = self.passlbbtx.text()
                        imgstrm = io.BytesIO(imgcon)
                        imgfile = Image.open(imgstrm)
                        self.passlb.setPixmap(ImageQt.toqpixmap(imgfile).scaled(250, 250))
    

    it runs but with an error message: "a bytes-like object is required, not 'str' "

    C Offline
    C Offline
    CEO.
    wrote on last edited by CEO.
    #21

    @CEO said in Appending an image to itemList of QFormLayout widgets:

    part of the sql data retrieval code:

                           result = self.cursor.fetchall()             
                         for row_number, row_data in enumerate(result):             
                             self.tab.insertRow(row_number)             
                             for column_number, data in enumerate(row_data):             
                                 self.tab.setItem(row_number, column_number, QTableWidgetItem(str(data)))
    

    it runs but with an error message: "a bytes-like object is required, not 'str' "

    Could the self.tab.setItem(row_number, column_number, QtablewidgetItem(str(data))) be where the issue is coming from?

    self.passlbtx is a QLineEdit for appending the varbinary data retrieved and displayed in a column of the qtablewidget.

    @mrjj

    mrjjM 1 Reply Last reply
    0
    • C CEO.

      @CEO said in Appending an image to itemList of QFormLayout widgets:

      part of the sql data retrieval code:

                             result = self.cursor.fetchall()             
                           for row_number, row_data in enumerate(result):             
                               self.tab.insertRow(row_number)             
                               for column_number, data in enumerate(row_data):             
                                   self.tab.setItem(row_number, column_number, QTableWidgetItem(str(data)))
      

      it runs but with an error message: "a bytes-like object is required, not 'str' "

      Could the self.tab.setItem(row_number, column_number, QtablewidgetItem(str(data))) be where the issue is coming from?

      self.passlbtx is a QLineEdit for appending the varbinary data retrieved and displayed in a column of the qtablewidget.

      @mrjj

      mrjjM Offline
      mrjjM Offline
      mrjj
      Lifetime Qt Champion
      wrote on last edited by
      #22

      Hi

      Well the
      QTableWidgetItem(str(data))
      part tried to make str out of data but it complains about the reverse
      "a bytes-like object is required, not 'str' "
      so I think it must be related to when you do the other way.

      I think maybe from here
      imgcon = bytes(self.passlbbtx.text(), 'utf-8')

      as QLineEdit only contains QString not Qbytearry or the binary stream you read from database.

      Would it not be possible to directly read it into the image/pixmap and not via a QLineEdit ?

      C 4 Replies Last reply
      0
      • mrjjM mrjj

        Hi

        Well the
        QTableWidgetItem(str(data))
        part tried to make str out of data but it complains about the reverse
        "a bytes-like object is required, not 'str' "
        so I think it must be related to when you do the other way.

        I think maybe from here
        imgcon = bytes(self.passlbbtx.text(), 'utf-8')

        as QLineEdit only contains QString not Qbytearry or the binary stream you read from database.

        Would it not be possible to directly read it into the image/pixmap and not via a QLineEdit ?

        C Offline
        C Offline
        CEO.
        wrote on last edited by
        #23

        @mrjj please kindly see this thread:

        https://github.com/python-pillow/Pillow/issues/5712

        1 Reply Last reply
        0
        • mrjjM mrjj

          Hi

          Well the
          QTableWidgetItem(str(data))
          part tried to make str out of data but it complains about the reverse
          "a bytes-like object is required, not 'str' "
          so I think it must be related to when you do the other way.

          I think maybe from here
          imgcon = bytes(self.passlbbtx.text(), 'utf-8')

          as QLineEdit only contains QString not Qbytearry or the binary stream you read from database.

          Would it not be possible to directly read it into the image/pixmap and not via a QLineEdit ?

          C Offline
          C Offline
          CEO.
          wrote on last edited by
          #24

          @mrjj I want the images to be changing as different row selection is made on the qtablewidget

          mrjjM 1 Reply Last reply
          0
          • C CEO.

            @mrjj I want the images to be changing as different row selection is made on the qtablewidget

            mrjjM Offline
            mrjjM Offline
            mrjj
            Lifetime Qt Champion
            wrote on last edited by mrjj
            #25

            @CEO
            Hi

            • I want the images to be changing as different row selection is made on the qtablewidget

            But are those rows a complete record and you want to show its image in its label or
            do you mean you click on some name in tablewidget and somewhere else it show
            the full record and you want to switch data there ?

            def retrieval(self):

            does this get the image ok ?
            That is also directly from DB.

            update:
            ah its names in listwidget and picture somewhere else.
            alt text

            C 1 Reply Last reply
            0
            • mrjjM mrjj

              @CEO
              Hi

              • I want the images to be changing as different row selection is made on the qtablewidget

              But are those rows a complete record and you want to show its image in its label or
              do you mean you click on some name in tablewidget and somewhere else it show
              the full record and you want to switch data there ?

              def retrieval(self):

              does this get the image ok ?
              That is also directly from DB.

              update:
              ah its names in listwidget and picture somewhere else.
              alt text

              C Offline
              C Offline
              CEO.
              wrote on last edited by
              #26

              @mrjj thanks for your effort.

              The table is a complete record. I wouldn't mind you use a teamviewer to access my system to see what I'm talking about. The qtablewidget is a complete record. Ignore those strange characters you see scattered there, it happened when I was trying some things.

              See the algorithm:

              When you click on the search button, all the records in the database are retrieved and get displayed on the qtablewidget cells. There are 22 attributes in the database table. I hid five (5) of them from being displayed on the qtablewidget. 17 gets displayed. The data for the photo in the database is varbinary but gets retrieved in the qtab as a string.

              Below the qtablewidget, I created a qformlayout with qwidgets. The QLineEdits are appended to the qtablewidget such that the record of any row selected will be displayed in their corresponding qLineEdit. one of the qlineEdits is self.passlbtx . This is for the photo data in the tablewidget column which is already in string.

              There is a qpixmap meant for the display of the photo of the selected row.

              The self.passlbtx qlineEdit data is already in string. So it is expected of the self.passlbtx qLineEdit data to be converted to byte and then jpg image so the image can display in the qpixmap.

              I know very well you can resolve it, I just think you're not understanding me. I believe it's a simple thing for you. I am attaching a photo to this post. In this photo, the first row of the qtab was selected (highlighted), thereby appending the data of the row in the qformlayout qlineEdits. Notice the image did not display, meanwhile there is a column for image data there, the texts of the image data is displayed in the qLineEdit of image byte label. So how do I make the image display in jpg or jpeg or png format in the qpixmap there?

              tabb.JPG

              1 Reply Last reply
              0
              • mrjjM Offline
                mrjjM Offline
                mrjj
                Lifetime Qt Champion
                wrote on last edited by
                #27

                Hi

                • So how do I make the image display in jpg or jpeg or png format in the qpixmap there
                  I think storing it in a LineEdit kills the data unless python can do something very magical.

                a you can see it shows as \x86\x8eu

                which is a text version of binay.

                So I think

                            imgcon = bytes(self.passlbbtx.text(), 'utf-8')
                            imgstrm = io.BytesIO(imgcon)
                            imgfile = Image.open(imgstrm)
                

                cannot work as self.passlbbtx.text() returns a text string and I'm not sure the bytes function understands that or at least
                get an image out of it.

                Would it be possible to directly load it from db on click in table instead of preloading it to a LineEdit ?

                C 3 Replies Last reply
                0
                • mrjjM mrjj

                  Hi

                  • So how do I make the image display in jpg or jpeg or png format in the qpixmap there
                    I think storing it in a LineEdit kills the data unless python can do something very magical.

                  a you can see it shows as \x86\x8eu

                  which is a text version of binay.

                  So I think

                              imgcon = bytes(self.passlbbtx.text(), 'utf-8')
                              imgstrm = io.BytesIO(imgcon)
                              imgfile = Image.open(imgstrm)
                  

                  cannot work as self.passlbbtx.text() returns a text string and I'm not sure the bytes function understands that or at least
                  get an image out of it.

                  Would it be possible to directly load it from db on click in table instead of preloading it to a LineEdit ?

                  C Offline
                  C Offline
                  CEO.
                  wrote on last edited by
                  #28

                  @mrjj said in Appending an image to itemList of QFormLayout widgets:

                  Hi

                  • So how do I make the image display in jpg or jpeg or png format in the qpixmap there
                    I think storing it in a LineEdit kills the data unless python can do something very magical.

                  a you can see it shows as \x86\x8eu

                  which is a text version of binay.

                  So I think

                              imgcon = bytes(self.passlbbtx.text(), 'utf-8')
                              imgstrm = io.BytesIO(imgcon)
                              imgfile = Image.open(imgstrm)
                  

                  cannot work as self.passlbbtx.text() returns a text string and I'm not sure the bytes function understands that or at least
                  get an image out of it.

                  Would it be possible to directly load it from db on click in table instead of preloading it to a LineEdit ?

                  if it's possible, I wouldn't mind giving it a trial, but without a qPixmap in the qtab, will it be possible?

                  1 Reply Last reply
                  0
                  • mrjjM mrjj

                    Hi

                    Well the
                    QTableWidgetItem(str(data))
                    part tried to make str out of data but it complains about the reverse
                    "a bytes-like object is required, not 'str' "
                    so I think it must be related to when you do the other way.

                    I think maybe from here
                    imgcon = bytes(self.passlbbtx.text(), 'utf-8')

                    as QLineEdit only contains QString not Qbytearry or the binary stream you read from database.

                    Would it not be possible to directly read it into the image/pixmap and not via a QLineEdit ?

                    C Offline
                    C Offline
                    CEO.
                    wrote on last edited by
                    #29

                    @mrjj said in Appending an image to itemList of QFormLayout widgets:

                    Would it not be possible to directly read it into the image/pixmap and not via a QLineEdit ?

                    When I tried to do this, it didn't work well with the fetchall() method, i.e result[the passport column]

                    It only works with fetchone() method.

                    Besides, using that would no longer be subjected to the row selection changes.

                    1 Reply Last reply
                    0
                    • mrjjM mrjj

                      Hi

                      Well the
                      QTableWidgetItem(str(data))
                      part tried to make str out of data but it complains about the reverse
                      "a bytes-like object is required, not 'str' "
                      so I think it must be related to when you do the other way.

                      I think maybe from here
                      imgcon = bytes(self.passlbbtx.text(), 'utf-8')

                      as QLineEdit only contains QString not Qbytearry or the binary stream you read from database.

                      Would it not be possible to directly read it into the image/pixmap and not via a QLineEdit ?

                      C Offline
                      C Offline
                      CEO.
                      wrote on last edited by
                      #30

                      @mrjj said in Appending an image to itemList of QFormLayout widgets:

                      Hi

                      Well the
                      QTableWidgetItem(str(data))
                      part tried to make str out of data but it complains about the reverse
                      "a bytes-like object is required, not 'str' "
                      so I think it must be related to when you do the other way.

                      I think maybe from here
                      imgcon = bytes(self.passlbbtx.text(), 'utf-8')

                      as QLineEdit only contains QString not Qbytearry or the binary stream you read from database.

                      Would it not be possible to directly read it into the image/pixmap and not via a QLineEdit ?

                      I tried to use this:

                                   self.tab.setItem(row_number, column_number, QTableWidgetItem(data if column_number == 7 else str(data)))
                      

                      It still says: "a bytes-like object is required, not 'str' "

                      1 Reply Last reply
                      0
                      • mrjjM mrjj

                        Hi

                        • So how do I make the image display in jpg or jpeg or png format in the qpixmap there
                          I think storing it in a LineEdit kills the data unless python can do something very magical.

                        a you can see it shows as \x86\x8eu

                        which is a text version of binay.

                        So I think

                                    imgcon = bytes(self.passlbbtx.text(), 'utf-8')
                                    imgstrm = io.BytesIO(imgcon)
                                    imgfile = Image.open(imgstrm)
                        

                        cannot work as self.passlbbtx.text() returns a text string and I'm not sure the bytes function understands that or at least
                        get an image out of it.

                        Would it be possible to directly load it from db on click in table instead of preloading it to a LineEdit ?

                        C Offline
                        C Offline
                        CEO.
                        wrote on last edited by
                        #31

                        @mrjj will it be possible I use the qtab column directly in my conversion?
                        For example:

                                     imgg = column7
                                     imgstrm = io.BytesIO(imgg)
                        

                        whereby column7 is the passport photo column in my qtable. Or is there a better way to instantiate it?

                        1 Reply Last reply
                        0
                        • mrjjM mrjj

                          Hi

                          • So how do I make the image display in jpg or jpeg or png format in the qpixmap there
                            I think storing it in a LineEdit kills the data unless python can do something very magical.

                          a you can see it shows as \x86\x8eu

                          which is a text version of binay.

                          So I think

                                      imgcon = bytes(self.passlbbtx.text(), 'utf-8')
                                      imgstrm = io.BytesIO(imgcon)
                                      imgfile = Image.open(imgstrm)
                          

                          cannot work as self.passlbbtx.text() returns a text string and I'm not sure the bytes function understands that or at least
                          get an image out of it.

                          Would it be possible to directly load it from db on click in table instead of preloading it to a LineEdit ?

                          C Offline
                          C Offline
                          CEO.
                          wrote on last edited by CEO.
                          #32

                          @mrjj

                          I had to do a sketch of what I want in another file, in a simpler way so as to reduce the codes but to pass the same message:

                          ```
                          

                          import sys
                          import pyodbc, uuid, os, hashlib, base64
                          from PyQt5 import QtWidgets, QtCore, QtGui
                          from PyQt5.QtWidgets import *
                          from PyQt5.QtGui import (QIcon, QFont, QPixmap)
                          from PyQt5.QtWidgets import *
                          from PyQt5.QtCore import *
                          import datetime, getpass, psutil, io
                          from random import randint as ri
                          from io import BytesIO, StringIO
                          from PIL import Image, ImageQt

                          class userRecords(QWidget):
                          def init(self):
                          super().init()
                          self.setGeometry(100, 100, 800, 700)

                              # setting the background stylesheet
                              self.setAutoFillBackground(True)
                              winP = self.palette()
                              winP.setColor(self.backgroundRole(), Qt.darkGray)
                              self.setPalette(winP)
                          
                              gridtab = QGridLayout()
                              gboxtab = QGroupBox()
                              gboxtab.setCheckable(True)
                              self.setLayout(gridtab)
                          
                              vboxtab = QVBoxLayout()
                              gboxtab.setLayout(vboxtab)
                          
                              hboxtab = QHBoxLayout()
                              hboxtab2 = QHBoxLayout()
                              vboxtab.addLayout(hboxtab)
                              vboxtab.addLayout(hboxtab2)
                          
                              self.tab = QtWidgets.QTableWidget(self)
                              gboxtab.setStyleSheet("background-color: powderblue")
                              self.tab.setStyleSheet("background-color: cornsilk; gridline-color: red; border: 2px solid gray; selection-color: yellow")
                          
                              self.searchbtn = QPushButton("Search:")
                              self.searchbtn.setStyleSheet("background-color: lightsteelblue; color: black")
                              self.searchbtn.clicked.connect(self.retrieve1)
                          
                              displaylb = QLabel("Selected row")
                              self.displaytx = QLineEdit()
                              self.displaytx.setReadOnly(True)
                              self.displaytx.setStyleSheet("background-color: moccasin;")
                          
                              global searchtxtab
                              searchtxtab = QLineEdit()
                              searchtxtab.setStyleSheet("background-color: moccasin;")
                          
                              clearbtn = QPushButton("Clear Records")
                              clearbtn.setStyleSheet("background-color: lightsteelblue; color: black")
                              clearbtn.clicked.connect(self.clearData)
                          
                              hboxtab.addWidget(self.searchbtn)
                              hboxtab.addWidget(searchtxtab)
                              hboxtab.addWidget(clearbtn)
                          
                              hboxtab2.addWidget(displaylb)
                              hboxtab2.addWidget(self.displaytx)
                          
                              vboxtab.addWidget(self.tab)
                          
                              gboxtab2 = QGroupBox()
                              fboxtab = QFormLayout()
                              hboxtab3 = QHBoxLayout()
                              vboxtab.addLayout(hboxtab3)
                              hboxtab3.addWidget(gboxtab2)
                              gboxtab2.setLayout(fboxtab)
                              gboxtab2.setStyleSheet("background-color: lightsteelblue")
                          
                          
                              gboxtab4 = QGroupBox()
                              fboxtab3 = QFormLayout()
                              hboxtab3.addWidget(gboxtab4)
                              gboxtab4.setLayout(fboxtab3)
                              gboxtab4.setCheckable(True)
                          
                              gboxtab5 = QGroupBox()
                              vboxtab2 = QVBoxLayout()
                              hboxtab3.addWidget(gboxtab5)
                              gboxtab5.setLayout(vboxtab2)
                          
                              gboxtab5.setCheckable(True)
                              gboxtab4.setStyleSheet("background-color: lightsteelblue")
                              gboxtab5.setStyleSheet("background-color: lightsteelblue")
                          
                              fulln = QLabel("Fullname:")
                              self.fulln = QLineEdit()
                              self.fulln.setStyleSheet("background-color: mistyrose;")
                          
                              deptlb = QLabel("Department:")
                              self.depttx = QLineEdit()
                              self.depttx.setStyleSheet("background-color: mistyrose;")
                          
                              quallb = QLabel("H.Qualification:")
                              self.qualtx = QLineEdit()
                              self.qualtx.setStyleSheet("background-color: mistyrose;")
                          
                              pspt = QLabel("Photo path:")
                              self.pspttx = QLineEdit()
                              self.pspttx.setStyleSheet("background-color: mistyrose;")
                          
                              self.passlb = QLabel("Passport Photo here")
                              self.passlb.setPixmap(QPixmap("C:\\Users\PC\\Pictures\\avaters\\avatar1.png").scaled(250,250))
                          
                              passlbb = QLabel("Image byte")
                              self.passlbbtx = QLineEdit()
                              self.passlbbtx.setStyleSheet("background-color: mistyrose;")
                              self.passlbbtx.setReadOnly(True)
                          
                              ptbtn = QPushButton("Upload Your Passport")
                              ptbtn.setStyleSheet("background-color: grey; color: navy; Font: 20px")
                              ptbtn.clicked.connect(self.openfile)
                          
                              fboxtab.addRow(fulln, self.fulln)
                              fboxtab.addRow(deptlb, self.depttx)
                              fboxtab.addRow(quallb, self.qualtx)
                          
                              fboxtab3.addRow(passlbb, self.passlbbtx)
                          
                              vboxtab2.addWidget(self.passlb)
                              vboxtab2.addWidget(ptbtn)
                          
                              scrol = QScrollArea()  # whatever you want to appear on the scrollArea must be coded before this scrollarea code
                              scrol.setWidget(gboxtab)
                              scrol.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
                              scrol.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
                              scrol.setWidgetResizable(True)
                              scrol.ensureVisible(1500, 1500)
                              gridtab.addWidget(scrol)
                          
                              Headerlist = ["Fullname", "Dept",  "H.Qualification", "Passport"]
                              self.tab.setRowCount(1000)
                              self.tab.setColumnCount(4)
                              self.tab.setHorizontalHeaderLabels(Headerlist)
                              # self.tab.horizontalHeader().setStyleSheet("::section{background-color: lightsteelblue}")
                              self.tab.horizontalHeader().setStyleSheet(
                                  "QHeaderView::section{background: lightsteelblue; padding- left: 4px; border: 3px solid red}")
                              self.tab.setGeometry(150, 200, 1700, 1700)
                              self.tab.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents)
                              self.tab.resizeColumnsToContents()
                              self.tab.setSelectionBehavior(QAbstractItemView.SelectRows)
                              self.tab.setSelectionMode(QAbstractItemView.SingleSelection)
                              self.tab.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # this makes the columns fit in the widget
                              self.tab.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)            # this makes the QTable widget uneditable.
                          
                              self.tab.setFont(QFont("Courier"))
                              self.tab.selectionModel().selectionChanged.connect(self.handle_selection_changed)
                          
                              self.msgBox = QMessageBox()
                              self.msgBox.setIcon(QMessageBox.Information)
                              self.msgBox.setGeometry(100, 100, 100, 100)
                              # self.update = updateRecord()
                          
                          def openfile(self):
                              try:
                                  fname, _ = QFileDialog.getOpenFileName(self, 'Open', 'c:\\', "image Files (*.jpg *.png)")
                                  self.pixlb.setPixmap(QPixmap(fname).scaled(250, 250))
                                  self.img = open(fname, 'rb')
                                  self.pixtx.setText(fname)
                                  print(self.pixlb.setText(''))
                          
                              except Exception as err:
                                  print(err)
                          
                          def db_connection(self):
                              try:
                                  # ensure there's no space before and after the = sign
                                  self.conn = pyodbc.connect('Driver={SQL Server}; Server=mine1;database=logistics; Trusted_Connection=yes;')
                                  self.cursor = self.conn.cursor()
                                  print("Connected to database")
                                  self.msgBox.setText("Program connected to database")
                                  self.msgBox.exec_()
                          
                              except Exception as err:
                                  print("couldn't connect")
                                  print("General error :: ", err)
                                  self.conn.close()
                                  dlg = QDialog(self)
                                  dlg.setWindowTitle("ALERT!")
                                  dlg.setGeometry(100, 100, 200, 100)
                                  dlg.move(300, 300)
                                  bb = QPushButton("ERROR!", dlg)
                                  bb.move(30, 50)
                                  dlg.exec_()
                          
                          def retrieve1(self):
                              try:
                                  self.db_connection()
                                  schbox = searchtxtab.text()  # to make the searchbox active, ensure it is coded close to the db connection.
                                  self.cursor.execute(
                                   " SELECT * FROM qTabTest WHERE fullname LIKE '%{}%' OR dept LIKE '%{}%' OR qual LIKE '%{}%' OR photo LIKE '%{}%' "
                                     .format(schbox, schbox, schbox, schbox))
                                  result = self.cursor.fetchall()
                          
                                  for row_number, row_data in enumerate(result):
                                      self.tab.insertRow(row_number)
                                      for column_number, data in enumerate(row_data):
                                          #self.tab.setItem(row_number, column_number, QTableWidgetItem(str(data)))
                                          self.tab.setItem(row_number, column_number,QTableWidgetItem(data if column_number == 3 else str(data)))
                                          #column 3 of the qtab is where the passport photo data is and I don't want it converted to string.
                          
                                  print(self.cursor.rowcount, "row(s) affected")
                                  self.conn.commit()
                                  msgBox = QMessageBox()
                                  msgBox.setIcon(QMessageBox.Information)
                                  msgBox.setText("DATA RETRIEVED")
                                  msgBox.setWindowTitle("MESSAGE FROM DB")
                                  msgBox.exec_()
                          
                              except Exception as err:
                                  print(err)
                                  self.conn.close()
                                  dlg = QDialog(self)
                                  dlg.setWindowTitle("ALERT!")
                                  dlg.setGeometry(100, 100, 200, 200)
                                  dlg.move(300, 300)
                                  dlg.setGeometry(100, 100, 200, 100)
                                  bb = QPushButton("ERROR", dlg)
                                  bb.move(30, 50)
                                  dlg.exec_()
                          
                              self.show()
                          
                          def handle_selection_changed(self):
                              rows = {
                                  index.row() for index in self.tab.selectionModel().selectedIndexes()
                              }
                              lines = []
                              for row in rows:
                                  texts = []
                                  for j in range(self.tab.columnCount()):
                                      item = self.tab.item(row, j)
                                      text = "" if item is None else item.text()
                                      texts.append(text)
                                  line = " ".join(texts)
                                  lines.append(line)
                              output = "\n".join(lines)
                              self.displaytx.setText(output)
                              self.appendSelection()
                          
                          def appendSelection(self):
                              try:
                                  rows = {index.row() for index in self.tab.selectionModel().selectedIndexes()}
                                  lines = []
                                  itemList = []
                          
                                  itemList.append(self.fulln)
                                  itemList.append(self.depttx)
                          
                                  itemList.append(self.qualtx)
                          
                                  itemList.append(self.passlbbtx)
                          
                          
                                 # itemList.append(self.passlb)
                          
                                  for row in rows:
                                      for col in range(self.tab.columnCount()):
                                          itemArray = self.tab.item(row, col)
                                          text = "" if itemArray is None else itemArray.text()
                                          if (col == 0):
                                              itemList[0].setText(text)
                                          if (col == 1):
                                              itemList[1].setText(text)
                                          if (col == 2):
                                              itemList[2].setText(text)
                                          if (col == 3):
                                              itemList[3].setText(text)
                          
                          
                              except Exception as err:
                                  print(err)
                          
                              print("This is passport bytes", self.passlbbtx.text())
                          
                          def clearData(self):
                              self.tab.clearContents()
                          

                          if name == 'main':
                          app = QApplication(sys.argv)
                          window = userRecords()
                          window.show()
                          app.exec()

                          
                          
                          
                          Here is the database table created in Microsoft SQL.
                          
                                                 CREATE TABLE qtabTest(
                          	           fullname varchar(100),
                          	            dept varchar(100),
                          	           qual varchar(50),
                          	          photo varbinary(max)
                          )
                          
                           I use pyodbc to connect with my Python code
                          1 Reply Last reply
                          0
                          • mrjjM Offline
                            mrjjM Offline
                            mrjj
                            Lifetime Qt Champion
                            wrote on last edited by
                            #33

                            Hi

                            so in your opinion the line
                            self.tab.setItem(row_number, column_number,QTableWidgetItem(data if column_number == 3 else str(data)))
                            should make sure the binary stream of the image, is kept safe as we don't call str on it ?

                            In c++ this would not work, but I don't know if python can do something magic.

                            If you can't get it to function, then you could try storing the image stream in a user role. its kept as QVariant so might work.

                            item = QTableWidgetItem("the text it should show")
                            MyRole = QtCore.Qt.UserRole + 2
                            item.setData(MyRole, data ) // data should be the real stream.

                            then when you click on a row and want the image
                            grab the item via one of the functions that directly gives it
                            https://doc.qt.io/qtforpython-5/PySide2/QtWidgets/QTableWidget.html#PySide2.QtWidgets.PySide2.QtWidgets.QTableWidget.itemChanged

                            and get the data back as
                            data = item.data(MyRole)
                            imgstrm = io.BytesIO(data)
                            imgfile = Image.open(imgstrm)

                            C 4 Replies Last reply
                            1
                            • mrjjM mrjj

                              Hi

                              so in your opinion the line
                              self.tab.setItem(row_number, column_number,QTableWidgetItem(data if column_number == 3 else str(data)))
                              should make sure the binary stream of the image, is kept safe as we don't call str on it ?

                              In c++ this would not work, but I don't know if python can do something magic.

                              If you can't get it to function, then you could try storing the image stream in a user role. its kept as QVariant so might work.

                              item = QTableWidgetItem("the text it should show")
                              MyRole = QtCore.Qt.UserRole + 2
                              item.setData(MyRole, data ) // data should be the real stream.

                              then when you click on a row and want the image
                              grab the item via one of the functions that directly gives it
                              https://doc.qt.io/qtforpython-5/PySide2/QtWidgets/QTableWidget.html#PySide2.QtWidgets.PySide2.QtWidgets.QTableWidget.itemChanged

                              and get the data back as
                              data = item.data(MyRole)
                              imgstrm = io.BytesIO(data)
                              imgfile = Image.open(imgstrm)

                              C Offline
                              C Offline
                              CEO.
                              wrote on last edited by
                              #34

                              @mrjj thanks for your follow-up, I discovered it made no difference. I'm talking about this line:

                                    self.tab.setItem(row_number, column_number,QTableWidgetItem(data if column_number == 3 else str(data)))
                              

                              The QTableWidgetItem is already in string, so whatever I print out from there would be in string. I tried it before.

                              1 Reply Last reply
                              0
                              • mrjjM mrjj

                                Hi

                                so in your opinion the line
                                self.tab.setItem(row_number, column_number,QTableWidgetItem(data if column_number == 3 else str(data)))
                                should make sure the binary stream of the image, is kept safe as we don't call str on it ?

                                In c++ this would not work, but I don't know if python can do something magic.

                                If you can't get it to function, then you could try storing the image stream in a user role. its kept as QVariant so might work.

                                item = QTableWidgetItem("the text it should show")
                                MyRole = QtCore.Qt.UserRole + 2
                                item.setData(MyRole, data ) // data should be the real stream.

                                then when you click on a row and want the image
                                grab the item via one of the functions that directly gives it
                                https://doc.qt.io/qtforpython-5/PySide2/QtWidgets/QTableWidget.html#PySide2.QtWidgets.PySide2.QtWidgets.QTableWidget.itemChanged

                                and get the data back as
                                data = item.data(MyRole)
                                imgstrm = io.BytesIO(data)
                                imgfile = Image.open(imgstrm)

                                C Offline
                                C Offline
                                CEO.
                                wrote on last edited by
                                #35

                                @mrjj please have you done something like this before? If yes, I wouldn't mind having a study of it, I might get one or two ideas on how to manipulate it in Python.

                                1 Reply Last reply
                                0
                                • mrjjM mrjj

                                  Hi

                                  so in your opinion the line
                                  self.tab.setItem(row_number, column_number,QTableWidgetItem(data if column_number == 3 else str(data)))
                                  should make sure the binary stream of the image, is kept safe as we don't call str on it ?

                                  In c++ this would not work, but I don't know if python can do something magic.

                                  If you can't get it to function, then you could try storing the image stream in a user role. its kept as QVariant so might work.

                                  item = QTableWidgetItem("the text it should show")
                                  MyRole = QtCore.Qt.UserRole + 2
                                  item.setData(MyRole, data ) // data should be the real stream.

                                  then when you click on a row and want the image
                                  grab the item via one of the functions that directly gives it
                                  https://doc.qt.io/qtforpython-5/PySide2/QtWidgets/QTableWidget.html#PySide2.QtWidgets.PySide2.QtWidgets.QTableWidget.itemChanged

                                  and get the data back as
                                  data = item.data(MyRole)
                                  imgstrm = io.BytesIO(data)
                                  imgfile = Image.open(imgstrm)

                                  C Offline
                                  C Offline
                                  CEO.
                                  wrote on last edited by
                                  #36

                                  @mrjj can you think over this line:

                                               self.tab.setItem(row_number, column_number,QTableWidgetItem(data if column_number == 12 else str(data)))
                                  

                                  ...and how I can convert the data there to bytes right there?

                                  1 Reply Last reply
                                  0
                                  • mrjjM mrjj

                                    Hi

                                    so in your opinion the line
                                    self.tab.setItem(row_number, column_number,QTableWidgetItem(data if column_number == 3 else str(data)))
                                    should make sure the binary stream of the image, is kept safe as we don't call str on it ?

                                    In c++ this would not work, but I don't know if python can do something magic.

                                    If you can't get it to function, then you could try storing the image stream in a user role. its kept as QVariant so might work.

                                    item = QTableWidgetItem("the text it should show")
                                    MyRole = QtCore.Qt.UserRole + 2
                                    item.setData(MyRole, data ) // data should be the real stream.

                                    then when you click on a row and want the image
                                    grab the item via one of the functions that directly gives it
                                    https://doc.qt.io/qtforpython-5/PySide2/QtWidgets/QTableWidget.html#PySide2.QtWidgets.PySide2.QtWidgets.QTableWidget.itemChanged

                                    and get the data back as
                                    data = item.data(MyRole)
                                    imgstrm = io.BytesIO(data)
                                    imgfile = Image.open(imgstrm)

                                    C Offline
                                    C Offline
                                    CEO.
                                    wrote on last edited by
                                    #37

                                    @mrjj said in Appending an image to itemList of QFormLayout widgets:

                                    item = QTableWidgetItem("the text it should show")
                                    MyRole = QtCore.Qt.UserRole + 2
                                    item.setData(MyRole, data )

                                    Error message: 'QTableWidget' object is not callable

                                    1 Reply Last reply
                                    0
                                    • C Offline
                                      C Offline
                                      CEO.
                                      wrote on last edited by
                                      #38

                                      I have finally resolved the issue:

                                      I decided to make the retrieved data display in the qtablewidget with the image displaying inside the qtablewidget (as a png, or jpg file) as it is retrieved from the database, so the varbinary texts no longer displays in the qtablewidget.

                                      Then I use the .loadData() method in displaying it there. I was able to resolve the appendSelection function and get the displayed image of the qtablewidget to display also in the qlabel qpixmap reserved for it in the qformlayout. This resolved the appending issue for me:

                                                                                    if (col == 2) and itemArray:
                                                                    
                                                                                        img = itemArray.data(QTableWidgetItem.UserType)
                                                                    
                                                                                        pixmap = QPixmap()
                                                                    
                                                                                        pixmap.loadFromData(img, 'jpg')
                                                                    
                                                                                        itemList[2].setPixmap(pixmap)
                                      
                                      mrjjM 1 Reply Last reply
                                      1
                                      • C CEO.

                                        I have finally resolved the issue:

                                        I decided to make the retrieved data display in the qtablewidget with the image displaying inside the qtablewidget (as a png, or jpg file) as it is retrieved from the database, so the varbinary texts no longer displays in the qtablewidget.

                                        Then I use the .loadData() method in displaying it there. I was able to resolve the appendSelection function and get the displayed image of the qtablewidget to display also in the qlabel qpixmap reserved for it in the qformlayout. This resolved the appending issue for me:

                                                                                      if (col == 2) and itemArray:
                                                                      
                                                                                          img = itemArray.data(QTableWidgetItem.UserType)
                                                                      
                                                                                          pixmap = QPixmap()
                                                                      
                                                                                          pixmap.loadFromData(img, 'jpg')
                                                                      
                                                                                          itemList[2].setPixmap(pixmap)
                                        
                                        mrjjM Offline
                                        mrjjM Offline
                                        mrjj
                                        Lifetime Qt Champion
                                        wrote on last edited by
                                        #39

                                        @CEO

                                        Super.
                                        So it helped not to store it in Linedit first but in a user role and
                                        hence it was not broken and could convert to image ?

                                        C 1 Reply Last reply
                                        0
                                        • mrjjM mrjj

                                          @CEO

                                          Super.
                                          So it helped not to store it in Linedit first but in a user role and
                                          hence it was not broken and could convert to image ?

                                          C Offline
                                          C Offline
                                          CEO.
                                          wrote on last edited by
                                          #40

                                          @mrjj yes and I was so happy and exclaimed EUREKA! immediately it worked fine. I now understand the joy Archimedes felt when the idea of upthrust struck him while bathing to the extent he had to run out of his bathroom naked. lol

                                          mrjjM 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