DiagramDesigner/common/include/tools.h

85 lines
2.6 KiB
C
Raw Normal View History

2025-04-17 16:51:20 +08:00
#ifndef TOOLS_H
#define TOOLS_H
#include <QHash>
2025-04-30 16:29:17 +08:00
#include <QStandardItem>
2025-04-17 16:51:20 +08:00
template <typename Key, typename Value> //双向map工具类实现key->value,value->key的映射
class BiDirectionalMap {
public:
// 插入键值对,确保双向唯一性
void insert(const Key& key, const Value& value) {
// 删除旧键和旧值的关联(如果存在)
if (m_keyToValue.contains(key)) {
Value oldValue = m_keyToValue[key];
m_valueToKey.remove(oldValue);
}
if (m_valueToKey.contains(value)) {
Key oldKey = m_valueToKey[value];
m_keyToValue.remove(oldKey);
}
// 插入新键值对
m_keyToValue[key] = value;
m_valueToKey[value] = key;
}
// 根据键获取值
Value value(const Key& key) const {
return m_keyToValue.value(key);
}
// 根据值获取键
Key key(const Value& value) const {
return m_valueToKey.value(value);
}
// 检查键是否存在
bool containsKey(const Key& key) const {
return m_keyToValue.contains(key);
}
// 检查值是否存在
bool containsValue(const Value& value) const {
return m_valueToKey.contains(value);
}
// 通过键删除项
void removeByKey(const Key& key) {
if (m_keyToValue.contains(key)) {
Value value = m_keyToValue[key];
m_keyToValue.remove(key);
m_valueToKey.remove(value);
}
}
// 通过值删除项
void removeByValue(const Value& value) {
if (m_valueToKey.contains(value)) {
Key key = m_valueToKey[value];
m_valueToKey.remove(value);
m_keyToValue.remove(key);
}
}
private:
QHash<Key, Value> m_keyToValue; // 键 → 值
QHash<Value, Key> m_valueToKey; // 值 → 键
};
2025-04-30 16:29:17 +08:00
int getLevel(QStandardItem *item);
2025-11-14 19:31:09 +08:00
QStandardItem* findStandardItemAtLevel(QStandardItemModel *model, int targetLevel,
const QString &targetText,
QStandardItem *parent = nullptr,
int currentLevel = 0);
QList<QStandardItem*> getAllChildren(QStandardItem* parentItem);
2025-05-16 19:20:46 +08:00
QModelIndex findIndex(const QAbstractItemModel* model, const QVariant& target,
int role = Qt::DisplayRole, const QModelIndex& parent = QModelIndex());
2025-06-27 19:17:04 +08:00
// 使用 clone() 方法深拷贝item
QStandardItem* deepCloneItem(const QStandardItem* source);
// 深拷贝整个模型(不复制表头)
QStandardItemModel* deepCloneModel(const QStandardItemModel* source);
2025-04-17 16:51:20 +08:00
#endif // DATABASE_H