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. Reading image from QSqlTableModel
Forum Updated to NodeBB v4.3 + New Features

Reading image from QSqlTableModel

Scheduled Pinned Locked Moved Unsolved General and Desktop
53 Posts 8 Posters 20.8k Views 4 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.
  • VRoninV VRonin
    • I don't like index.column() == NUMBER_OF_PIXMAP_COLUMN as it ties the delegate to a single model so I consider it bad design, view->setItemDelegateForColumn() should be used instead.
    • index.data( ROLE_USED_IN_MODEL ) it's a QSqlTableModel so just delete ROLE_USED_IN_MODEL and use the default
    • It's a QStyledItemDelegate so let's use style
    void FixViewDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const {
    QPixmap loadedImage;
    loadedImage.loadFromData(index.data().toByteArray());
    const QWidget *widget = option.widget;
    QStyle *style = widget ? widget->style() : QApplication::style();
    style->drawItemPixmap(painter,option.rect,Qt::AlignCenter,loadedImage);
    }
    
    G Offline
    G Offline
    gabor53
    wrote on last edited by
    #38

    @VRonin
    Thank you. It runs without error, but paint nothing in the view.

    1 Reply Last reply
    0
    • VRoninV Offline
      VRoninV Offline
      VRonin
      wrote on last edited by
      #39

      How do you save your image in the database? do you save it via Qt? can you show us the save part of the code?

      "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
      ~Napoleon Bonaparte

      On a crusade to banish setIndexWidget() from the holy land of Qt

      G 1 Reply Last reply
      0
      • VRoninV VRonin

        How do you save your image in the database? do you save it via Qt? can you show us the save part of the code?

        G Offline
        G Offline
        gabor53
        wrote on last edited by gabor53
        #40

        @VRonin
        Sure. I also added

         qDebug() << "loadedImage size: " << loadedImage.size ();
        

        and the result is
        loadedImage size: QSize(0, 0)

        I save the image via Qt like this:

        #include "review.h"
        #include "ui_review.h"
        
        Review::Review(QWidget* parent) :
          QDialog(parent),
          ui(new Ui::Review) {
          ui->setupUi(this);
        
          connect(this, &Review::RecAdded, this, &Review::updateTable);
        
        }
        
        Review::~Review() {
          delete ui;
        }
        
        void Review::dispRev(QString sID, QString& name, QString& whatChosen, QString& fileNameChosen, QString& materialChosen, QString& colorChosen, QString& description, QDate& adoptDate, QString& SignedbyChosen, QString& history, QString& age, QString& notesTemp) {
          name = name.simplified ();
          description = description.simplified ();
        
          ui->ID_display_Label->setText (sID);
          ui->Name_Disp_Label->setText (name);
          ui->What_Display_Label->setText (whatChosen);
          ui->MadeOf_Disp_Label->setText (materialChosen);
          ui->Color_Disp_Label->setText (colorChosen);
          ui->textBrowser_Descr->setText (description);
          adoptDateStr = adoptDate.toString ("MM/dd/yyyy");
          ui->AdoptionDate_Disp_Label->setText (adoptDateStr);
          ui->SignedBy_Disp_label->setText (SignedbyChosen);
          ui->textBrowser_History->setText (history);
          ui->Age_Display_Label_2->setText (age);
          ui->textBrowser_Notes->setText (notesTemp);
        
        
          QPixmap pix2(fileNameChosen);
          int w = 0;
          int h = 0;
          w = ui->Image_Display_Label->width ();
          h = ui->Image_Display_Label->height ();
          ui->Image_Display_Label->setPixmap (pix2.scaled(w, h, Qt::KeepAspectRatio));
        
          QFile fileReview(fileNameChosen);
        
          if(fileReview.open (QIODevice::ReadOnly)) {
            fileByteArray = fileReview.readAll ();
          }
        
          nameReview = name;
          whatReview = whatChosen;
          fileNameReview = fileNameChosen;
          materialReview = materialChosen;
          colorReview = colorChosen;
          descriptionReview = description;
          adoptDateReview = adoptDate;
          SignedbyReview = SignedbyChosen;
          historyReview = history;
          sIDReview = sID;
          ageReview = age;
          notesReview = notesTemp;
        
        }
        
        
        void Review::on_pushButton_Add_to_DB_clicked() {
        
        //    date = adoptDateReview.toString ("MM/dd/yyyy");
          qDebug() << "date in review.cpp: " << date;
          QSqlDatabase db = QSqlDatabase::addDatabase ("QSQLITE", "writedb");
          db.setDatabaseName (fileQstring);
        
          QSqlQuery querys(db);
        
          if(!db.open ())
        
          {
            qDebug() << "The database is not open (submit)!";
          } else {
            qDebug() << "The database is open (submit)!";
          }
          querys.prepare("INSERT INTO Items (ID, Name, Pic, Description, AdoptDate, History, Age, Notes, Color, Material, Signed, What) VALUES(:ID, :Name, :Pic, :Description, :AdoptDate, :History, :Age, :Notes, :Color, :Material, :Signed, :What)" );
          querys.bindValue (":ID", sIDReview);
          querys.bindValue (":Name", nameReview);
          querys.bindValue (":Pic", fileByteArray);
          querys.bindValue (":Description", descriptionReview);
          querys.bindValue (":AdoptDate", adoptDateStr);
          querys.bindValue (":History", historyReview);
          querys.bindValue (":Age", ageReview);
          querys.bindValue (":Notes", notesReview);
          querys.bindValue (":Color", colorReview);
          querys.bindValue (":Material", materialReview);
          querys.bindValue (":Signed", SignedbyReview);
          querys.bindValue (":What", whatReview);
        
          bool result = querys.exec ();
        
          if(!result) {
            qDebug() << "Error inserting into the main db!" << querys.lastError ();
        
            QMessageBox::warning (this, "Add to Database Warning", "<b><font size='16' color='red'>Error 1002: The Friend was not added to the database.");
        
          } else {
            qDebug() << "Entered FunctAdd OK loop.";
        
            QMessageBox::information (this, "Confirmation", "<b><font size = '16' color = 'green'>The Friend was added to the database.</font>");
        
        
        
            emit RecAdded ();
          }
        }
        
        
        void Review::on_pushButton_Fix_clicked() {
          Additem* mAdditem = new Additem(this);
          mAdditem->FixFriend (sIDReview, nameReview, whatReview, fileNameReview, materialReview, colorReview, descriptionReview, date, SignedbyReview, historyReview, ageReview, notesReview);
        
        
          mAdditem->show ();
        }
        
        
        void Review::updateTable() {
          qDebug() << "Entered updateTable!";
          MainWindow* mMainWindow = new MainWindow(this);
        
          mMainWindow->Addview ();
          mMainWindow->show ();
        }
        
        

        Data in the db is stored as BLOB.

        1 Reply Last reply
        0
        • SGaistS Offline
          SGaistS Offline
          SGaist
          Lifetime Qt Champion
          wrote on last edited by
          #41

          You don't do anything in case fileReview.open fails so you might be storing empty QByteArrays in your database.

          Interested in AI ? www.idiap.ch
          Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

          G 1 Reply Last reply
          0
          • SGaistS SGaist

            You don't do anything in case fileReview.open fails so you might be storing empty QByteArrays in your database.

            G Offline
            G Offline
            gabor53
            wrote on last edited by gabor53
            #42

            @SGaist
            I tried to add a record and I got an error message:
            The database is open (submit)!
            Error inserting into the main db! QSqlError("", "Parameter count mismatch", "")

            I'm not sure this has anything to do with the original issue.
            I checked a Pic field in the db using DB Browser and there is binary data in the Pic column.
            I also made the following changes:

             if(loadedImage.loadFromData (index.data ().toByteArray ()) != true) {
                qDebug() << "Fiximage not loaded";
              } else {
                qDebug() << "Fiximage IS loaded";
              };
              
            

            The result was Fiximage not loaded

            1 Reply Last reply
            0
            • VRoninV Offline
              VRoninV Offline
              VRonin
              wrote on last edited by VRonin
              #43

              Error inserting into the main db! QSqlError("", "Parameter count mismatch", "")

              I'm not sure this has anything to do with the original issue

              It does.

              SQLite some/all of Qt's SQLite drivers do not support named binding and apparently Qt is not smart enough to go around it seamlessly.

              use positional binding instead, see http://doc.qt.io/qt-5/qsqlquery.html#approaches-to-binding-values

              You should use the ? version instead of the :id version.

              You can check what your database can do using db.driver()->hasFeature() in your case db.driver()->hasFeature(QSqlDriver::NamedPlaceholders) will return false

              EDIT:

              @SGaist is right, corrected my post

              "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
              ~Napoleon Bonaparte

              On a crusade to banish setIndexWidget() from the holy land of Qt

              1 Reply Last reply
              0
              • SGaistS Offline
                SGaistS Offline
                SGaist
                Lifetime Qt Champion
                wrote on last edited by
                #44

                @VRonin SQLite does since some times already and Qt 5.10 should have proper support for that. Until then, positional is the safest way as you wrote.

                Interested in AI ? www.idiap.ch
                Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                G 1 Reply Last reply
                1
                • SGaistS SGaist

                  @VRonin SQLite does since some times already and Qt 5.10 should have proper support for that. Until then, positional is the safest way as you wrote.

                  G Offline
                  G Offline
                  gabor53
                  wrote on last edited by gabor53
                  #45

                  @SGaist
                  I redid the query like this:

                  (ID,Name,Pic,What,Material,Color,Description,AdoptDate,Signed,History,Age,Notes)" "VALUES(?,?,?,?,?,?,?,?,?,?,?,?)");
                    querys.bindValue (0, sIDReview);
                    querys.bindValue (1, nameReview);
                    querys.bindValue (2, fileByteArray);
                    querys.bindValue (3, whatReview);
                    querys.bindValue (4, materialReview);
                    querys.bindValue (5, colorReview);
                    querys.bindValue (6, descriptionReview);
                    querys.bindValue (7, adoptDateStr);
                    querys.bindValue (8, SignedbyReview);
                    querys.bindValue (9, historyReview);
                    querys.bindValue (10, ageReview);
                    querys.bindValue (11, notesReview);
                  
                    bool result = querys.exec ();
                  
                  

                  It gave me this error :

                  Error inserting into the main db! QSqlError("", "Parameter count mismatch", "")
                  External WM_DESTROY received for QWidgetWindow(0x24d75c10, name="ReviewWindow") , parent: QWindow(0x0) , transient parent: QWidgetWindow(0x24d7a4b0, name="AdditemWindow")

                  Changing

                   explicit Review(QWidget* parent = 0);
                  

                  to

                   explicit Review(QWidget* parent = Q_NULLPTR);
                  

                  in review.h
                  solved everything except the Parameter count mismatch.

                  1 Reply Last reply
                  0
                  • VRoninV Offline
                    VRoninV Offline
                    VRonin
                    wrote on last edited by
                    #46

                    can you try using addBindValue instead of bindValue?

                    "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
                    ~Napoleon Bonaparte

                    On a crusade to banish setIndexWidget() from the holy land of Qt

                    G 1 Reply Last reply
                    0
                    • VRoninV VRonin

                      can you try using addBindValue instead of bindValue?

                      G Offline
                      G Offline
                      gabor53
                      wrote on last edited by
                      #47

                      @VRonin
                      I changed as you recommended:

                       querys.prepare ("INSERT INTO Items (ID,Name,Pic,What,Material,Color,Description,AdoptDate,Signed,History,Age,Notes)" "VALUES(?,?,?,?,?,?,?,?,?,?,?,?)");
                        querys.addBindValue (sIDReview);
                        querys.addBindValue (nameReview);
                        querys.addBindValue (fileByteArray);
                        querys.addBindValue (whatReview);
                        querys.addBindValue (materialReview);
                        querys.addBindValue (colorReview);
                        querys.addBindValue (descriptionReview);
                        querys.addBindValue (adoptDateStr);
                        querys.addBindValue (SignedbyReview);
                        querys.addBindValue (historyReview);
                        querys.addBindValue (ageReview);
                        querys.addBindValue (notesReview);
                      
                        bool result = querys.exec ();
                      

                      Still the same error message.

                      1 Reply Last reply
                      0
                      • SGaistS Offline
                        SGaistS Offline
                        SGaist
                        Lifetime Qt Champion
                        wrote on last edited by
                        #48

                        Do you have anything null/invalid that you pass to addBindValue ?

                        Interested in AI ? www.idiap.ch
                        Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                        G 2 Replies Last reply
                        1
                        • SGaistS SGaist

                          Do you have anything null/invalid that you pass to addBindValue ?

                          G Offline
                          G Offline
                          gabor53
                          wrote on last edited by
                          #49

                          @SGaist
                          Nothing invalid, but I had a bunch of blank text fields which I'm sure translate into null.

                          1 Reply Last reply
                          0
                          • SGaistS SGaist

                            Do you have anything null/invalid that you pass to addBindValue ?

                            G Offline
                            G Offline
                            gabor53
                            wrote on last edited by
                            #50

                            @SGaist
                            Even when I fill out each field I get the same error.

                            1 Reply Last reply
                            0
                            • SGaistS Offline
                              SGaistS Offline
                              SGaist
                              Lifetime Qt Champion
                              wrote on last edited by
                              #51

                              Don't you have a missing space in your query between the ) and VALUES ?

                              Interested in AI ? www.idiap.ch
                              Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                              G 1 Reply Last reply
                              0
                              • SGaistS SGaist

                                Don't you have a missing space in your query between the ) and VALUES ?

                                G Offline
                                G Offline
                                gabor53
                                wrote on last edited by
                                #52

                                @SGaist
                                I tried to add space between the " " or ) " but made no difference.
                                I rebuilt the db and now the images are displayed, but they are all rotated 90° left; no idea why.

                                1 Reply Last reply
                                0
                                • P Offline
                                  P Offline
                                  patrik08
                                  wrote on last edited by patrik08
                                  #53

                                  Image debug is not simple... but Base64 is a nice way..
                                  i hope to render you idea...
                                  source on https://github.com/pehohlva/QOASIS/blob/master/test/dkernel/sys/core_htmldriver.cpp
                                  to display RTFD documents + image from mac.
                                  by patrik

                                  /*   image to html display whitout image link & play in qt4/qt5 */ 
                                  QByteArray HtmlDriver::pic_encode( QImage im )  {
                                      int w=im.width();
                                      int h=im.height();
                                      QByteArray bytes;
                                     //// scale if to big
                                      if (w > 550 ) {
                                          im.scaled(550,550, Qt::KeepAspectRatio);
                                      }
                                      QBuffer buffer(&bytes);
                                      buffer.open(QIODevice::WriteOnly);
                                      im.save(&buffer, "PNG");
                                     /// save inside buffer ram
                                      if (bytes.size() > 0) {
                                      QByteArray blueimag = bytes.toBase64();
                                      QByteArray orderpic("data:image/png;base64,");
                                      orderpic.append(blueimag);
                                      return orderpic;
                                     /// and insert inside image src=
                                      } else {
                                        /// if image is brocken 1x1 pixel transparent...  but 95% image pass.
                                          return QByteArray("data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==");
                                      }
                                  }
                                  
                                  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