i
ironexmaiden24. August 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
Stabiles Hosting des sozialen Netzwerks EVILEG. Wir empfehlen VDS-Hosting für Django-Projekte.

Magst du es? In sozialen Netzwerken teilen!

9
Evgenii Legotckoi
  • 25. August 2017 02: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. August 2017 03: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. August 2017 03:45
      • (bearbeitet)

      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. August 2017 04: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. August 2017 04: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. August 2017 04:25
            • (bearbeitet)

            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. August 2017 04: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. August 2017 04: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. August 2017 04:34

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

                    Kommentare

                    Nur autorisierte Benutzer können Kommentare posten.
                    Bitte Anmelden oder Registrieren
                    Letzte Kommentare
                    A
                    ALO1ZE19. Oktober 2024 08:19
                    Fb3-Dateileser auf Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
                    ИМ
                    Игорь Максимов5. Oktober 2024 07:51
                    Django – Lektion 064. So schreiben Sie eine Python-Markdown-Erweiterung Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
                    d
                    dblas55. Juli 2024 11:02
                    QML - Lektion 016. SQLite-Datenbank und das Arbeiten damit in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
                    k
                    kmssr8. Februar 2024 18:43
                    Qt Linux - Lektion 001. Autorun Qt-Anwendung unter Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
                    Qt WinAPI - Lektion 007. Arbeiten mit ICMP-Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
                    Jetzt im Forum diskutieren
                    J
                    JacobFib17. Oktober 2024 03:27
                    добавить qlineseries в функции Пользователь может получить любые разъяснения по интересующим вопросам, касающимся обработки его персональных данных, обратившись к Оператору с помощью электронной почты https://topdecorpro.ru…
                    JW
                    Jhon Wick1. Oktober 2024 15:52
                    Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
                    КГ
                    Кирилл Гусарев27. September 2024 09:09
                    Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
                    F
                    Fynjy22. Juli 2024 04:15
                    при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

                    Folgen Sie uns in sozialen Netzwerken