Я начинаю изучать QT, и мне нужна помощь с структурированием моего приложения. Идея состоит в том, чтобы управлять всеми данными в одном месте, чтобы я мог легко сохранить/загрузить все - или определенные детали - один раз.class EntryData
{
public:
explicit EntryData();
QString name() const;
void setName(const QString& name);
private:
QString m_fullName;
};
// Serialization
QDataStream &operator(QDataStream& in, EntryData& data);
< /code>
class TodoListModel : public QAbstractListModel
{
Q_OBJECT
public:
enum EntryRoles {
FullNameRole
};
explicit TodoListModel(QObject* parent = nullptr);
~TodoListModel();
Q_INVOKABLE void add(const QString& name);
Q_INVOKABLE void insertAt(const QString& name, int row);
Q_INVOKABLE void removeAt(int row, int count = 1);
// ~ Begin QAbstractListModel interface
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override;
Qt::ItemFlags flags(const QModelIndex& index) const override;
// ~ End QAbstractListModel interface
const QVector& entries() const;
protected:
// ~ Begin QAbstractListModel interface
QHash roleNames() const override;
// ~ End QAbstractListModel interface
private:
QVector m_entryList;
signals:
void rowCountChanged();
};
< /code>
I also want to implement methods to save/load the data, as well as track the loading state:
class TodoListModel;
class DataManager : public QObject
{
Q_OBJECT
Q_PROPERTY(bool isLoading READ isLoading NOTIFY loadingChanged)
private:
explicit DataManager(QObject *parent = nullptr);
public:
static QObject* createInstance(QQmlEngine* engine, QJSEngine* scriptEngine);
Q_INVOKABLE void save(const QString& path);
Q_INVOKABLE bool load(const QString& path);
Q_INVOKABLE void setModel(TodoListModel* model);
bool isLoading() const;
private:
void emitLoading(bool value);
private:
static DataManager* s_instance;
TodoListModel* m_model = nullptr;
//UserSettingsModel* m_userSettings = nullptr;
bool m_isLoading = false;
signals:
void loadingChanged();
};
< /code>
and here is the example implementation of save function:
void DataManager::save(const QString &path)
{
if (m_isLoading) {
return;
}
emitLoading(true);
// Async save all data
(void)QtConcurrent::run([this, path]() {
QFile file(path);
if (!file.open(QIODevice::WriteOnly) || m_model == nullptr) {
emitLoading(false);
return;
}
QDataStream out(&file);
out entries();
file.close();
emitLoading(false);
});
}
< /code>
My question is: Is this a good approach? I'm looking for best practices or patterns for managing data in a Qt app, but I haven’t found much documentation or examples.
Any guidance or suggestions would be appreciated!
Подробнее здесь: https://stackoverflow.com/questions/797 ... -singleton
Лучшая практика для глобальной обработки данных с использованием синглтона? ⇐ C++
Программы на C++. Форум разработчиков
1754156928
Anonymous
Я начинаю изучать QT, и мне нужна помощь с структурированием моего приложения. Идея состоит в том, чтобы управлять всеми данными в одном месте, чтобы я мог легко сохранить/загрузить все - или определенные детали - один раз.class EntryData
{
public:
explicit EntryData();
QString name() const;
void setName(const QString& name);
private:
QString m_fullName;
};
// Serialization
QDataStream &operator(QDataStream& in, EntryData& data);
< /code>
class TodoListModel : public QAbstractListModel
{
Q_OBJECT
public:
enum EntryRoles {
FullNameRole
};
explicit TodoListModel(QObject* parent = nullptr);
~TodoListModel();
Q_INVOKABLE void add(const QString& name);
Q_INVOKABLE void insertAt(const QString& name, int row);
Q_INVOKABLE void removeAt(int row, int count = 1);
// ~ Begin QAbstractListModel interface
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override;
Qt::ItemFlags flags(const QModelIndex& index) const override;
// ~ End QAbstractListModel interface
const QVector& entries() const;
protected:
// ~ Begin QAbstractListModel interface
QHash roleNames() const override;
// ~ End QAbstractListModel interface
private:
QVector m_entryList;
signals:
void rowCountChanged();
};
< /code>
I also want to implement methods to save/load the data, as well as track the loading state:
class TodoListModel;
class DataManager : public QObject
{
Q_OBJECT
Q_PROPERTY(bool isLoading READ isLoading NOTIFY loadingChanged)
private:
explicit DataManager(QObject *parent = nullptr);
public:
static QObject* createInstance(QQmlEngine* engine, QJSEngine* scriptEngine);
Q_INVOKABLE void save(const QString& path);
Q_INVOKABLE bool load(const QString& path);
Q_INVOKABLE void setModel(TodoListModel* model);
bool isLoading() const;
private:
void emitLoading(bool value);
private:
static DataManager* s_instance;
TodoListModel* m_model = nullptr;
//UserSettingsModel* m_userSettings = nullptr;
bool m_isLoading = false;
signals:
void loadingChanged();
};
< /code>
and here is the example implementation of save function:
void DataManager::save(const QString &path)
{
if (m_isLoading) {
return;
}
emitLoading(true);
// Async save all data
(void)QtConcurrent::run([this, path]() {
QFile file(path);
if (!file.open(QIODevice::WriteOnly) || m_model == nullptr) {
emitLoading(false);
return;
}
QDataStream out(&file);
out entries();
file.close();
emitLoading(false);
});
}
< /code>
My question is: Is this a good approach? I'm looking for best practices or patterns for managing data in a Qt app, but I haven’t found much documentation or examples.
Any guidance or suggestions would be appreciated!
Подробнее здесь: [url]https://stackoverflow.com/questions/79723544/best-practice-for-global-data-handling-using-a-singleton[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия