i
ironexmaidenТам. 24, 2017, 5: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

                    Пікірлер

                    Тек рұқсаты бар пайдаланушылар ғана пікір қалдыра алады.
                    Кіріңіз немесе Тіркеліңіз
                    Г

                    C++ - Тест 001. Первая программа и типы данных

                    • Нәтиже:66ұпай,
                    • Бағалау ұпайлары-1
                    t

                    C++ - Тест 001. Первая программа и типы данных

                    • Нәтиже:33ұпай,
                    • Бағалау ұпайлары-10
                    t

                    Qt - Тест 001. Сигналы и слоты

                    • Нәтиже:52ұпай,
                    • Бағалау ұпайлары-4
                    Соңғы пікірлер
                    G
                    GoattRockҚыр. 3, 2024, 1:50 Т.Қ.
                    Linux жүйесінде файлдарды қалай көшіруге болады Задумывались когда-нибудь о том, как мы привыкли доверять свои вещи службам грузоперевозок? Сейчас такие услуги стали неотъемлемой частью нашей жизни, особенно когда речь идет о переездах между …
                    d
                    dblas5Шілде 5, 2024, 11:02 Т.Ж.
                    QML - Сабақ 016. SQLite деректер қоры және онымен QML Qt-та жұмыс істеу Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
                    k
                    kmssrАқп. 8, 2024, 6:43 Т.Қ.
                    Qt Linux - Сабақ 001. Linux астында Autorun Qt қолданбасы как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
                    АК
                    Анатолий КононенкоАқп. 5, 2024, 1:50 Т.Ж.
                    Qt WinAPI - Сабақ 007. Qt ішінде ICMP Ping арқылы жұмыс істеу Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
                    Енді форумда талқылаңыз
                    Evgenii Legotckoi
                    Evgenii LegotckoiМаусым 24, 2024, 3:11 Т.Қ.
                    добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
                    F
                    FynjyШілде 22, 2024, 4:15 Т.Ж.
                    при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …
                    BlinCT
                    BlinCTМаусым 25, 2024, 1 Т.Ж.
                    Нарисовать кривую в qml Всем привет. Имеется Лист листов с тосками, точки получаны интерполяцией Лагранжа. Вопрос, как этими точками нарисовать кривую? ChartView отпадает сразу, в qt6.7 появился новый элемент…
                    BlinCT
                    BlinCTМамыр 5, 2024, 5:46 Т.Ж.
                    Написать свой GraphsView Всем привет. В Qt есть давольно старый обьект дял работы с графиками ChartsView и есть в 6.7 новый но очень сырой и со слабым функционалом GraphsView. По этой причине я хочу написать х…
                    Evgenii Legotckoi
                    Evgenii LegotckoiМамыр 2, 2024, 2:07 Т.Қ.
                    Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Добрый день. По моему мнению - да, но то, что будет касаться вызовов к функционалу Андроида, может создать огромные трудности.

                    Бізді әлеуметтік желілерде бақылаңыз