DiagramDesigner/common/include/tools.h

80 lines
2.3 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#ifndef TOOLS_H
#define TOOLS_H
#include <QHash>
#include <QStandardItem>
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; // 值 → 键
};
int getLevel(QStandardItem *item);
QModelIndex findIndex(const QAbstractItemModel* model, const QVariant& target,
int role = Qt::DisplayRole, const QModelIndex& parent = QModelIndex());
// 使用 clone() 方法深拷贝item
QStandardItem* deepCloneItem(const QStandardItem* source);
// 深拷贝整个模型(不复制表头)
QStandardItemModel* deepCloneModel(const QStandardItemModel* source);
#endif // DATABASE_H