class TreeNode { friend class GroupModel; public: explicit TreeNode(const…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
class TreeNode { friend class GroupModel; public: explicit TreeNode(const QList& data, TreeNode* parent = nullptr) : m_nodeData(data), m_parent(parent) {}
~TreeNode() {
qDeleteAll(m_children);
}
void appendChild(TreeNode* child) {
m_children.append(child);
}
TreeNode* child(int row) {
return m_children.value(row);
}
int childCount() const {
return m_children.count();
}
int columnCount() const {
return m_nodeData.count();
}
QVariant data(int column) const {
return m_nodeData.value(column);
}
QList<QVariant> rawData()
{
return m_nodeData;
}
int row() const {
if (m_parent)
return m_parent->m_children.indexOf(const_cast<TreeNode*>(this));
return 0;
}
TreeNode* parent() {
return m_parent;
}
void clear()
{
for (auto obj : m_children)
{
delete obj;
}
m_children.clear();
}
TreeNode* findGroupByID(int id)
{
if (m_nodeData.length()>2&&m_nodeData[1].toBool()&&m_nodeData[2].toInt()==id)
{
return this;
}
for (auto node:m_children)
{
TreeNode * ret=node->findGroupByID(id);
if (ret!=nullptr)
{
return ret;
}
}
return nullptr;
}
private: QList<TreeNode*> m_children; QList m_nodeData; //对于分组节点,第一个值是分组名称,第二个值是true,第三个值是分组ID TreeNode* m_parent = nullptr; }; class GroupModel : public QAbstractItemModel { Q_OBJECT
public: explicit GroupModel(const QStringList& headers, QObject* parent = nullptr) : QAbstractItemModel(parent), m_rootNode(new TreeNode(QList())) { QList rootData; for (const QString& header : headers) { rootData << header; } m_rootNode = new TreeNode(rootData); }
~GroupModel() override {
delete m_rootNode;
}
// 基本模型接口实现
QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override {
if (!hasIndex(row, column, parent)) {
return QModelIndex();
}
TreeNode* parentNode = nodeFromIndex(parent);
TreeNode* childNode = parentNode->child(row);
return childNode ? createIndex(row, column, childNode) : QModelIndex();
}
QModelIndex parent(const QModelIndex& index) const override {
if (!index.isValid()) {
return QModelIndex();
}
TreeNode* childNode = nodeFromIndex(index);
TreeNode* parentNode = childNode->parent();
if (parentNode == m_rootNode) {
return QModelIndex();
}
return createIndex(parentNode->row(), 0, parentNode);
}
int rowCount(const QModelIndex& parent = QModelIndex()) const override {
if (parent.column() > 0) {
return 0;
}
TreeNode* parentNode = nodeFromIndex(parent);
return parentNode->childCount();
}
int columnCount(const QModelIndex& parent = QModelIndex()) const override {
return m_rootNode->columnCount();
}
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override {
if (!index.isValid() ) {
return QVariant();
}
TreeNode* node = nodeFromIndex(index);
if (role == Qt::UserRole)
return node->rawData();
else if(role==Qt::DisplayRole)
return node->data(index.column());
return QVariant();
}
QVariant headerData(int section, Qt::Orientation orientation, int role) const override {
if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
return m_rootNode->data(section);
}
return QVariant();
}
Qt::ItemFlags flags(const QModelIndex& index) const override {
if (!index.isValid()) {
return Qt::NoItemFlags;
}
return QAbstractItemModel::flags(index);
}
TreeNode* getRootNode() { return m_rootNode; }
//节点操作
TreeNode* findGroupByID(int id)
{
return m_rootNode->findGroupByID(id);
}
//添加子分组
void newGroup(QModelIndex index,int id, int parentID, const QString& groupName)
{
TreeNode* parentNode = (parentID == -1) ? m_rootNode : findGroupByID(parentID);
if (!parentNode) return;
int row = parentNode->childCount();
// 关键修改:判断是否是根节点,根节点使用空索引
QModelIndex parentIndex=parentNode == m_rootNode?QModelIndex(): createIndex(parentNode->row(), 0, parentNode);
beginInsertRows(parentIndex, row, row);
QList<QVariant> groupNodeData;
groupNodeData << groupName << true << id;
TreeNode* newGroup = new TreeNode(groupNodeData, parentNode);
parentNode->appendChild(newGroup);
endInsertRows();
}
//重命名
void newName(const QModelIndex& index, const QString& newName)
{
if (!index.isValid())return;
TreeNode* node = nodeFromIndex(index);
node->m_nodeData[0] = newName;
emit dataChanged(index, index);
}
//删除节点及其所有子节点
void del(const QModelIndex& index)
{
if (!index.isValid())
return;
TreeNode* node = nodeFromIndex(index);
TreeNode* parentNode = node->parent();
if (!parentNode)
return;
int row = node->row();
beginRemoveRows(parent(index), row, row);
delGroupAndArticle(node);
parentNode->m_children.removeAt(row);
QSqlQuery query;
query.prepare("DELETE FROM T_Group WHERE id=:groupid");
query.bindValue(":groupid", node->m_nodeData[2].toInt());
if (query.exec())
delete node;
endRemoveRows();
}
void delGroupAndArticle(TreeNode* node)
{
// 先处理子节点
while (!node->m_children.isEmpty()) {
TreeNode* childNode = node->m_children.first();
if (childNode->m_nodeData[1].toBool()) { // 分组节点
delGroupAndArticle(childNode);
QSqlQuery query;
query.prepare("DELETE FROM T_Group WHERE id=:groupid");
query.bindValue(":groupid", childNode->m_nodeData[2].toInt());
if (query.exec()) {
node->m_children.removeOne(childNode);
delete childNode;
}
}
else { // 网文节点
QSqlQuery query;
query.prepare("DELETE FROM T_Article WHERE id=:articleID");
query.bindValue(":articleID", childNode->m_nodeData[2].toInt());
if (query.exec()) {
node->m_children.removeOne(childNode);
delete childNode;
}
}
}
}
private: TreeNode* nodeFromIndex(const QModelIndex& index) const { if (!index.isValid()) { return m_rootNode; } else { return static_cast<TreeNode*>(index.internalPointer()); } }
TreeNode* m_rootNode;
}; 对应的数据库表格结构:CREATE TABLE T_Group ( ID INTEGER PRIMARY KEY AUTOINCREMENT, GroupName TEXT UNIQUE NOT NULL, ParentID INTEGER NOT NULL ); 请根据上市内容完善优化代码
你提供的代码实现了一个基于树形结构的分组模型 GroupModel,并且与数据库表 T_Group 进行了关联。整体设计已经比较完整,但仍有一些可以优化和完善的地方,尤其是数据库操作的安全性、模型与数据库同步、代码风格和性能方面。下面我将给出详细的优化建议和改进示例。
QSqlQuery::exec() 返回 false 时应打印错误日志,方便调试。delGroupAndArticle 中对每个子节点都执行删除操作,建议改为递归删除并统一提交事务。newGroup 只在内存中添加节点,未同步插入数据库,建议补充插入数据库的逻辑,并获取自增ID。newName 修改了内存数据,但未更新数据库。TreeNode 中的 clear() 函数可以用 qDeleteAll 替代手动循环。findGroupByID 函数中,m_nodeData.length()>2 建议用 columnCount() 替代硬编码。newGroup 中 QModelIndex index 参数未使用,可以去掉。delGroupAndArticle 函数中,删除子节点时建议先从数据库删除,再从内存删除,避免内存泄漏。nodeFromIndex 函数可以加 Q_ASSERT 以保证安全。// 1. newGroup 同步数据库,返回新节点指针
TreeNode* newGroup(int parentID, const QString& groupName)
{
TreeNode* parentNode = (parentID == -1) ? m_rootNode : findGroupByID(parentID);
if (!parentNode) return nullptr;
// 插入数据库
QSqlQuery query;
query.prepare("INSERT INTO T_Group (GroupName, ParentID) VALUES (:name, :parentID)");
query.bindValue(":name", groupName);
query.bindValue(":parentID", parentID);
if (!query.exec()) {
qWarning() << "Insert group failed:" << query.lastError().text();
return nullptr;
}
int newID = query.lastInsertId().toInt();
int row = parentNode->childCount();
QModelIndex parentIndex = (parentNode == m_rootNode) ? QModelIndex() : createIndex(parentNode->row(), 0, parentNode);
beginInsertRows(parentIndex, row, row);
QList<QVariant> groupNodeData{groupName, true, newID};
TreeNode* newGroup = new TreeNode(groupNodeData, parentNode);
parentNode->appendChild(newGroup);
endInsertRows();
return newGroup;
}
// 2. newName 同步数据库
void newName(const QModelIndex& index, const QString& newName)
{
if (!index.isValid()) return;
TreeNode* node = nodeFromIndex(index);
int id = node->rawData().value(2).toInt();
QSqlQuery query;
query.prepare("UPDATE T_Group SET GroupName = :name WHERE ID = :id");
query.bindValue(":name", newName);
query.bindValue(":id", id);
if (!query.exec()) {
qWarning() << "Update group name failed:" << query.lastError().text();
return;
}
node->m_nodeData[0] = newName;
emit dataChanged(index, index);
}
// 3. delGroupAndArticle 使用事务递归删除
void delGroupAndArticle(TreeNode* node)
{
QSqlDatabase::database().transaction();
std::function<void(TreeNode*)> recursiveDelete = [&](TreeNode* n) {
for (auto child : n->m_children) {
if (child->m_nodeData[1].toBool()) { // 分组
recursiveDelete(child);
QSqlQuery query;
query.prepare("DELETE FROM T_Group WHERE ID = :id");
query.bindValue(":id", child->m_nodeData[2].toInt());
if (!query.exec()) {
qWarning() << "Delete group failed:" << query.lastError().text();
}
} else { // 文章
QSqlQuery query;
query.prepare("DELETE FROM T_Article WHERE ID = :id");
query.bindValue(":id", child->m_nodeData[2].toInt());
if (!query.exec()) {
qWarning() << "Delete article failed:" << query.lastError().text();
}
}
delete child;
}
n->m_children.clear();
};
recursiveDelete(node);
QSqlQuery query;
query.prepare("DELETE FROM T_Group WHERE ID = :id");
query.bindValue(":id", node->m_nodeData[2].toInt());
if (!query.exec()) {
qWarning() << "Delete group failed:" << query.lastError().text();
}
QSqlDatabase::database().commit();
}
// 4. nodeFromIndex 增加断言
TreeNode* nodeFromIndex(const QModelIndex& index) const {
if (!index.isValid()) {
return m_rootNode;
}
TreeNode* node = static_cast<TreeNode*>(index.internalPointer());
Q_ASSERT(node != nullptr);
return node;
}
setData(),支持编辑模型数据。如果需要,我可以帮你写完整的示例代码或实现某个功能模块。你觉得呢?