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 5.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.
  • 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
                    • C CEO.

                      @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 Offline
                      mrjjM Offline
                      mrjj
                      Lifetime Qt Champion
                      wrote on last edited by
                      #41

                      @CEO

                      hehe well good :)
                      thx for the feedback. I learn by knowing what was wrong so it was as i
                      guessed at. the binary stream didn't like to be in lineedit first.

                      C 1 Reply Last reply
                      0
                      • mrjjM mrjj

                        @CEO

                        hehe well good :)
                        thx for the feedback. I learn by knowing what was wrong so it was as i
                        guessed at. the binary stream didn't like to be in lineedit first.

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

                        @mrjj

                        .

                        I wanna update the retrieved image which is displayed in jpg format. How do I go about it plz?

                        The image label (i.e the qpixmap label) is self.passlb

                         if (col == 2) and itemArray:
                                            img = itemArray.data(QTableWidgetItem.UserType)
                                            pixmap = QPixmap()
                                            pixmap.loadFromData(img, 'jpg')
                                            itemList[2].setPixmap((pixmap).scaled(250,250))
                        

                        So in my sql update statement, I tried:

                                     values(self.fullname.text(),
                                     self.passlb.pixmap()
                        ...)```
                        
                        It didn't work.
                        
                        Do you think it should be:
                        
                               img.pixmap() or img.text() or img.read()
                        Any clue about the method I should use in updating a qpixmap label?
                        mrjjM 1 Reply Last reply
                        0
                        • C CEO.

                          @mrjj

                          .

                          I wanna update the retrieved image which is displayed in jpg format. How do I go about it plz?

                          The image label (i.e the qpixmap label) is self.passlb

                           if (col == 2) and itemArray:
                                              img = itemArray.data(QTableWidgetItem.UserType)
                                              pixmap = QPixmap()
                                              pixmap.loadFromData(img, 'jpg')
                                              itemList[2].setPixmap((pixmap).scaled(250,250))
                          

                          So in my sql update statement, I tried:

                                       values(self.fullname.text(),
                                       self.passlb.pixmap()
                          ...)```
                          
                          It didn't work.
                          
                          Do you think it should be:
                          
                                 img.pixmap() or img.text() or img.read()
                          Any clue about the method I should use in updating a qpixmap label?
                          mrjjM Offline
                          mrjjM Offline
                          mrjj
                          Lifetime Qt Champion
                          wrote on last edited by mrjj
                          #43

                          Hi
                          You mean save an actual pixmap back to the database ?`

                          But what is the type of field in the db and how did you get the other images in there ?

                          Its clear we need to convert it to a binary stream and we can use QBuffer for that

                          (c++, could not find python example)

                              QPixmap inPixmap =self.passlb.pixmap(); 
                              QByteArray inByteArray;
                              QBuffer inBuffer( &inByteArray );
                              inBuffer.open( QIODevice::WriteOnly );
                              inPixmap.save( &inBuffer, "PNG" ); // write inPixmap into inByteArray in PNG format
                          

                          inBuffer can now be saved in DB.

                          But I wonder if there is the reverse of io.BytesIO ? we should rather use ?

                          C 1 Reply Last reply
                          0
                          • mrjjM mrjj

                            Hi
                            You mean save an actual pixmap back to the database ?`

                            But what is the type of field in the db and how did you get the other images in there ?

                            Its clear we need to convert it to a binary stream and we can use QBuffer for that

                            (c++, could not find python example)

                                QPixmap inPixmap =self.passlb.pixmap(); 
                                QByteArray inByteArray;
                                QBuffer inBuffer( &inByteArray );
                                inBuffer.open( QIODevice::WriteOnly );
                                inPixmap.save( &inBuffer, "PNG" ); // write inPixmap into inByteArray in PNG format
                            

                            inBuffer can now be saved in DB.

                            But I wonder if there is the reverse of io.BytesIO ? we should rather use ?

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

                            @mrjj sorry,

                            See this function, it's for uploading images in the form for update:

                            def openfile(self):
                                try:
                                    fname, _ = QFileDialog.getOpenFileName(self, 'Open', 'c:\\', "image Files (*.jpg *.png)")
                                    self.passlb.setPixmap(QPixmap(fname).scaled(250, 250))
                                    self.img = open(fname, 'rb')
                                    self.psptpath.setText(fname)
                                    # self.pixL.setText(strfn)
                                    print(self.pixlb.setText(''))
                            

                            This function is for appending the jpg to the qlabel self.passlb from the qtable after it's been retrieved from the database:

                                   if (col ==2):
                                   img = itemArray.data(QTableWidgetItem.UserType)
                                                           pixmap = QPixmap()
                                                           pixmap.loadFromData(img, 'jpg')
                                                           itemList[2].setPixmap((pixmap).scaled(250,250))
                            

                            Then here is my sql statement updating the image:
                            (The usual update statement is here)
                            values (self.fullname.text(),
                            self.img.read()
                            )

                            This is saying my program objects has no attribute 'img'

                            mrjjM C 3 Replies Last reply
                            0
                            • C CEO.

                              @mrjj sorry,

                              See this function, it's for uploading images in the form for update:

                              def openfile(self):
                                  try:
                                      fname, _ = QFileDialog.getOpenFileName(self, 'Open', 'c:\\', "image Files (*.jpg *.png)")
                                      self.passlb.setPixmap(QPixmap(fname).scaled(250, 250))
                                      self.img = open(fname, 'rb')
                                      self.psptpath.setText(fname)
                                      # self.pixL.setText(strfn)
                                      print(self.pixlb.setText(''))
                              

                              This function is for appending the jpg to the qlabel self.passlb from the qtable after it's been retrieved from the database:

                                     if (col ==2):
                                     img = itemArray.data(QTableWidgetItem.UserType)
                                                             pixmap = QPixmap()
                                                             pixmap.loadFromData(img, 'jpg')
                                                             itemList[2].setPixmap((pixmap).scaled(250,250))
                              

                              Then here is my sql statement updating the image:
                              (The usual update statement is here)
                              values (self.fullname.text(),
                              self.img.read()
                              )

                              This is saying my program objects has no attribute 'img'

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

                              @CEO
                              ah well its better with such logical bug than something that just don't work :)

                              C 1 Reply Last reply
                              0
                              • C CEO.

                                @mrjj sorry,

                                See this function, it's for uploading images in the form for update:

                                def openfile(self):
                                    try:
                                        fname, _ = QFileDialog.getOpenFileName(self, 'Open', 'c:\\', "image Files (*.jpg *.png)")
                                        self.passlb.setPixmap(QPixmap(fname).scaled(250, 250))
                                        self.img = open(fname, 'rb')
                                        self.psptpath.setText(fname)
                                        # self.pixL.setText(strfn)
                                        print(self.pixlb.setText(''))
                                

                                This function is for appending the jpg to the qlabel self.passlb from the qtable after it's been retrieved from the database:

                                       if (col ==2):
                                       img = itemArray.data(QTableWidgetItem.UserType)
                                                               pixmap = QPixmap()
                                                               pixmap.loadFromData(img, 'jpg')
                                                               itemList[2].setPixmap((pixmap).scaled(250,250))
                                

                                Then here is my sql statement updating the image:
                                (The usual update statement is here)
                                values (self.fullname.text(),
                                self.img.read()
                                )

                                This is saying my program objects has no attribute 'img'

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

                                @mrjj please see this.

                                1 Reply Last reply
                                0
                                • C CEO.

                                  @mrjj sorry,

                                  See this function, it's for uploading images in the form for update:

                                  def openfile(self):
                                      try:
                                          fname, _ = QFileDialog.getOpenFileName(self, 'Open', 'c:\\', "image Files (*.jpg *.png)")
                                          self.passlb.setPixmap(QPixmap(fname).scaled(250, 250))
                                          self.img = open(fname, 'rb')
                                          self.psptpath.setText(fname)
                                          # self.pixL.setText(strfn)
                                          print(self.pixlb.setText(''))
                                  

                                  This function is for appending the jpg to the qlabel self.passlb from the qtable after it's been retrieved from the database:

                                         if (col ==2):
                                         img = itemArray.data(QTableWidgetItem.UserType)
                                                                 pixmap = QPixmap()
                                                                 pixmap.loadFromData(img, 'jpg')
                                                                 itemList[2].setPixmap((pixmap).scaled(250,250))
                                  

                                  Then here is my sql statement updating the image:
                                  (The usual update statement is here)
                                  values (self.fullname.text(),
                                  self.img.read()
                                  )

                                  This is saying my program objects has no attribute 'img'

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

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

                                  @mrjj sorry,

                                  See this function, it's for uploading images in the form for update:

                                  def openfile(self):
                                      try:
                                          fname, _ = QFileDialog.getOpenFileName(self, 'Open', 'c:\\', "image Files (*.jpg *.png)")
                                          self.passlb.setPixmap(QPixmap(fname).scaled(250, 250))
                                          self.img = open(fname, 'rb')
                                          self.psptpath.setText(fname)
                                          # self.pixL.setText(strfn)
                                          print(self.pixlb.setText(''))
                                  

                                  This function is for appending the jpg to the qlabel self.passlb from the qtable after it's been retrieved from the database:

                                         if (col ==2):
                                         img = itemArray.data(QTableWidgetItem.UserType)
                                                                 pixmap = QPixmap()
                                                                 pixmap.loadFromData(img, 'jpg')
                                                                 itemList[2].setPixmap((pixmap).scaled(250,250))
                                  

                                  Then here is my sql statement updating the image:
                                  (The usual update statement is here)
                                  values (self.fullname.text(),
                                  self.img.read()
                                  )

                                  This is saying my program objects has no attribute 'img'

                                  @mrjj

                                  1 Reply Last reply
                                  0
                                  • mrjjM mrjj

                                    @CEO
                                    ah well its better with such logical bug than something that just don't work :)

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

                                    @mrjj I did some testing and discovered it works fine only when I update the photo. Updating any other column without updating the image (photo) produces an error saying no object found for the image column.

                                    mrjjM 1 Reply Last reply
                                    0
                                    • C CEO.

                                      @mrjj I did some testing and discovered it works fine only when I update the photo. Updating any other column without updating the image (photo) produces an error saying no object found for the image column.

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

                                      @CEO
                                      But does it says that self.img don't exists ?

                                      but in def openfile(self):

                                      self.img = open(fname, 'rb')

                                      works

                                      so is the function that uses the SQL, also part of the same class ?

                                      C 1 Reply Last reply
                                      0
                                      • mrjjM mrjj

                                        @CEO
                                        But does it says that self.img don't exists ?

                                        but in def openfile(self):

                                        self.img = open(fname, 'rb')

                                        works

                                        so is the function that uses the SQL, also part of the same class ?

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

                                        @mrjj the function that uses the SQL is part of the class. It works fine when in my update I upload a photo but comes up with that error "object has no attribute 'img' " if I don't upload a photo (i.e when I leave the photo retrieved from the database). Meaning even if I upload the same photo there, it will work. It just wants the upload to be done in that pixmap field

                                        mrjjM 1 Reply Last reply
                                        0
                                        • C CEO.

                                          @mrjj the function that uses the SQL is part of the class. It works fine when in my update I upload a photo but comes up with that error "object has no attribute 'img' " if I don't upload a photo (i.e when I leave the photo retrieved from the database). Meaning even if I upload the same photo there, it will work. It just wants the upload to be done in that pixmap field

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

                                          So when loading from db, you need to both set the UserRole and the pixmap field
                                          it sounds like even the error "object has no attribute 'img' " is very confusing
                                          if it is indeed a class member.

                                          1 Reply Last reply
                                          0

                                          • Login

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