i
ironexmaiden24 августа 2017 г. 17:05

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(); 
    }
Рекомендуем хостинг TIMEWEB
Рекомендуем хостинг TIMEWEB
Стабильный хостинг, на котором располагается социальная сеть EVILEG. Для проектов на Django рекомендуем VDS хостинг.

Вам это нравится? Поделитесь в социальных сетях!

9
Evgenii Legotckoi
  • 25 августа 2017 г. 2:49

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
    • 25 августа 2017 г. 3:41

    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
      • 25 августа 2017 г. 3:45
      • (ред.)

      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
        • 25 августа 2017 г. 4:14

        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
          • 25 августа 2017 г. 4:20
           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
            • 25 августа 2017 г. 4:25
            • (ред.)

            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
              • 25 августа 2017 г. 4:30

              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
                • 25 августа 2017 г. 4:32

                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
                  • 25 августа 2017 г. 4:34

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

                    Комментарии

                    Только авторизованные пользователи могут публиковать комментарии.
                    Пожалуйста, авторизуйтесь или зарегистрируйтесь
                    г
                    • ги
                    • 23 апреля 2024 г. 15:51

                    C++ - Тест 005. Структуры и Классы

                    • Результат:41баллов,
                    • Очки рейтинга-8
                    l
                    • laei
                    • 23 апреля 2024 г. 9:19

                    C++ - Тест 004. Указатели, Массивы и Циклы

                    • Результат:10баллов,
                    • Очки рейтинга-10
                    l
                    • laei
                    • 23 апреля 2024 г. 9:17

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

                    • Результат:50баллов,
                    • Очки рейтинга-4
                    Последние комментарии
                    k
                    kmssr8 февраля 2024 г. 18:43
                    Qt Linux - Урок 001. Автозапуск Qt приложения под Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
                    АК
                    Анатолий Кононенко5 февраля 2024 г. 1:50
                    Qt WinAPI - Урок 007. Работаем с ICMP Ping в Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
                    EVA
                    EVA25 декабря 2023 г. 10:30
                    Boost - статическая линковка в CMake проекте под Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
                    J
                    JonnyJo25 декабря 2023 г. 8:38
                    Boost - статическая линковка в CMake проекте под Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
                    G
                    Gvozdik18 декабря 2023 г. 21:01
                    Qt/C++ - Урок 056. Подключение библиотеки Boost в Qt для компиляторов MinGW и MSVC Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
                    Сейчас обсуждают на форуме
                    G
                    Gar22 апреля 2024 г. 5:46
                    Clipboard Как скопировать окно целиком в clipb?
                    DA
                    Dr Gangil Academics20 апреля 2024 г. 7:45
                    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_vlasov14 апреля 2024 г. 6:41
                    Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
                    Павел Дорофеев
                    Павел Дорофеев14 апреля 2024 г. 2:35
                    QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
                    f
                    fastrex4 апреля 2024 г. 4:47
                    Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

                    Следите за нами в социальных сетях