i
ironexmaidenAug. 24, 2017, 5:05 p.m.

QTableView connected with QSqlTableModel flickers (scrolls to the bottom and returns)

qt, qsql, QSqlDataBase, QSqlTableModel, QTableView

Hello guys I have a problem using table view. I have a tableview connected with a QSqlTableModel. On its 2nd column I want to have check state to control the row's Status (active/inactive) but when I try to push the check box QTableView scrolls to the bottom and returns to it's previous position. Is there any solution?

    bool ProjectsModel::setData(const QModelIndex &index, const QVariant &value, int role)
    {
        if(index.column() == STATUS_INDEX) {
            QSqlRecord rec = this->record(index.row());
            QString qrstr;
     
            qrstr = (rec.field(index.column()).value().toInt() == 1) ? "update " + tableName() + " set Status=0 where BRACE_ID=" : "update " + tableName() + " set Status=1 where BRACE_ID=";
            qrstr += QString().setNum(index.row()+1);
     
            braceDatabase->exec(qrstr.toUtf8().constData());
            return true;
        }
     
        return false;
    }
     
    void DataBase::updateTablesSlot()
    {
        if(projectsModel)
            projectsModel->select();
        if(attributesModel)
            attributesModel->select();
        if(targetsModel)
            targetsModel->select();
    }
     
    void DataBase::exec(const std::string &querystr)
    {
    		QSqlQuery qr(db);
            qr.exec(querystr.c_str());
            //qDebug() <<"Command :" << querystr.c_str() << "-> "<< query->lastError().text();
            updateTables(); 
    }
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

9
Evgenii Legotckoi
  • Aug. 25, 2017, 2:49 a.m.

Hello!
I think you need to use QItemDelegate for this (or same claas which was inherited from this class). Or You can use QTableWidget.
You can research article with checkboxes in QTableWidget .
May be it will be usefull for You.

    Evgenii Legotckoi
    • Aug. 25, 2017, 3:41 a.m.

    And may be you need use for scroll method scrollTo()

    For this You should to save QModelIndex with which you work now, and after getting information from SQL DataBase, You should invoke method scrollTo(storedIndex) for scroll to needed position.
      i
      • Aug. 25, 2017, 3:45 a.m.
      • (edited)

      Hello my friend and thank you for the help unfortunately I can't use QTableWidget for performance reasons, I must load big databases from csv files.  If I try the second solution with the scroll It will have a disturbing effect the table will hop up and down every time the user presses the check state.

      Christos,
      Greeting from Thessaloniki, Greece

        Evgenii Legotckoi
        • Aug. 25, 2017, 4:14 a.m.

        Ok. May be You need to use custom ItemDelegate for this.


        class CheckBoxDelegate: public QItemDelegate
        {
            Q_OBJECT
        public:
            CheckBoxDelegate(QObject *parent = 0);
        
            void paint( QPainter *painter,
                                const QStyleOptionViewItem &option,
                                const QModelIndex &index ) const;
        
        
            QWidget *createEditor( QWidget *parent,
                                const QStyleOptionViewItem &option,
                                const QModelIndex &index ) const;
        
            void setEditorData( QWidget *editor,
                                const QModelIndex &index ) const;
        
            void setModelData( QWidget *editor,
                                QAbstractItemModel *model,
                                const QModelIndex &index ) const;
        
            void updateEditorGeometry( QWidget *editor,
                                const QStyleOptionViewItem &option,
                                const QModelIndex &index ) const;
        
            mutable QCheckBox * theCheckBox;
        
        private slots:
        
            void setData(bool val);
        
        
        };
        And set delegate
        ui->myTable->setItemDelegateForColumn(5,new CheckBoxDelegate(ui->myTable));

        Best Regards from Prague.
          i
          • Aug. 25, 2017, 4:20 a.m.
           QString qrstr;
               
                      qrstr = (rec.field(index.column()).value().toInt() == 1) ? "update " + tableName() + " set Status=0 where BRACE_ID=" : "update " + tableName() + " set Status=1 where BRACE_ID=";
                      qrstr += QString().setNum(index.row()+1);
               
                      braceDatabase->exec(qrstr.toUtf8().constData());
          Thank you my friend I will check this solution and I will report keep on mind that another guy informed me that the query exec clears the model and reset the data, and this reset is the reason of the flickering he proposed me the solution of QSqlTableModel::setData
          I changed my code to this one but the check state on click didn't change :(
              bool AttributesModel::setData(const QModelIndex &index, const QVariant &value, int role)
              {
                  if(index.column() == STATUS_INDEX) {
                      bool ret = QSqlTableModel::setData(index, value == Qt::Checked ? Qt::Unchecked : Qt::Checked, role);
                      database().commit();
                      this->submitAll();
                      return ret;
                  }
                  return QSqlTableModel::setData(index, value, role);
              }
            Evgenii Legotckoi
            • Aug. 25, 2017, 4:25 a.m.
            • (edited)

            I am not sure, but problem of this solution may be in Qt::Checked and Qt::Unchecked. 

            Because this enum has 3 states

            enum CheckState {
                    Unchecked,
                    PartiallyChecked,
                    Checked
                };
            • Unchecked = 0
            • PartiallyChecked = 1
            • Checked = 2
            But You use two states 0 and 1 in your csv files, if I see correctly.
              i
              • Aug. 25, 2017, 4:30 a.m.

              That's the point I want the status of the row to be Active/Inactive PartiallyChecked option is useless for me. Do you refer that I had an error on this line ?

              bool ret = QSqlTableModel::setData(index, value == Qt::Checked ? Qt::Unchecked : Qt::Checked, role);
                Evgenii Legotckoi
                • Aug. 25, 2017, 4:32 a.m.

                I am not sure, but may be you can try to check the following code in this row:

                bool ret = QSqlTableModel::setData(index, value == Qt::Checked ? 0 : 1, role);
                  i
                  • Aug. 25, 2017, 4:34 a.m.

                  Hmm you may be right I will check it EVILEG and I will report later thank you

                    Comments

                    Only authorized users can post comments.
                    Please, Log in or Sign up
                    г
                    • ги
                    • April 24, 2024, 1:51 a.m.

                    C++ - Test 005. Structures and Classes

                    • Result:41points,
                    • Rating points-8
                    l
                    • laei
                    • April 23, 2024, 7:19 p.m.

                    C ++ - Test 004. Pointers, Arrays and Loops

                    • Result:10points,
                    • Rating points-10
                    l
                    • laei
                    • April 23, 2024, 7:17 p.m.

                    C++ - Тест 003. Условия и циклы

                    • Result:50points,
                    • Rating points-4
                    Last comments
                    k
                    kmssrFeb. 9, 2024, 5:43 a.m.
                    Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
                    Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
                    EVA
                    EVADec. 25, 2023, 9:30 p.m.
                    Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
                    J
                    JonnyJoDec. 25, 2023, 7:38 p.m.
                    Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
                    G
                    GvozdikDec. 19, 2023, 8:01 a.m.
                    Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
                    Now discuss on the forum
                    G
                    GarApril 22, 2024, 3:46 p.m.
                    Clipboard Как скопировать окно целиком в clipb?
                    DA
                    Dr Gangil AcademicsApril 20, 2024, 5:45 p.m.
                    Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
                    a
                    a_vlasovApril 14, 2024, 4:41 p.m.
                    Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
                    Павел Дорофеев
                    Павел ДорофеевApril 14, 2024, 12:35 p.m.
                    QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
                    f
                    fastrexApril 4, 2024, 2:47 p.m.
                    Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

                    Follow us in social networks