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
Стабільний хостинг, на якому розміщується соціальна мережа EVILEG. Для проектів на Django радимо VDS хостинг.Вам це подобається? Поділіться в соціальних мережах!
sf
- sdfsdfkp fgskpgokspdog
- 14 жовтня 2024 р. 15:09
C++ - Тест 004. Указатели, Массивы и Циклы
- Результат:90бали,
- Рейтинг балів8
МВ
- Максим Васильев
- 02 жовтня 2024 р. 04:14
Qt - Тест 001. Сигналы и слоты
- Результат:68бали,
- Рейтинг балів-1
ЛС
- Лев Семенов
- 30 вересня 2024 р. 11:04
C++ - Тест 001. Первая программа и типы данных
- Результат:53бали,
- Рейтинг балів-4
Останні коментарі
Читалка файлів fb3 на Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Django - Урок 064. Як написати розширення для Python Markdown Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
Игорь Максимов05 жовтня 2024 р. 07:51
QML - Урок 016. База даних SQLite та робота з нею в QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Qt Linux - Урок 001. Автозапуск програми Qt під Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
АК
Qt WinAPI - Урок 007. Робота з ICMP Ping в Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
Анатолий Кононенко05 лютого 2024 р. 01:50
Тепер обговоріть на форумі
добавить qlineseries в функции Пользователь может получить любые разъяснения по интересующим вопросам, касающимся обработки его персональных данных, обратившись к Оператору с помощью электронной почты https://topdecorpro.ru…
ИМ
Реализация навигации по разделам Спасибо Евгений!
Игорь Максимов03 жовтня 2024 р. 04:05
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…
КГ
Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
Кирилл Гусарев27 вересня 2024 р. 09:09
при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …
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.
And may be you need use for scroll method scrollTo()
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
Ok. May be You need to use custom ItemDelegate for this.
And set delegate
Best Regards from Prague.
I changed my code to this one but the check state on click didn't change :(
I am not sure, but problem of this solution may be in Qt::Checked and Qt::Unchecked.
Because this enum has 3 states
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 ?
I am not sure, but may be you can try to check the following code in this row:
Hmm you may be right I will check it EVILEG and I will report later thank you