DbTreeViewManager.cpp 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743
  1. #include "DbTreeViewManager.h"
  2. #include "OriginalWnd/OriginalWnd.h"
  3. #include "OriginalWnd/NonInteractiveCheckDelegate.h"
  4. // 构造函数
  5. DbTreeViewManager::DbTreeViewManager(OriginalWnd* originalWnd, QWidget* widget2, QWidget* parent)
  6. : QWidget(parent),
  7. m_originalWnd(originalWnd),
  8. widget2(widget2),
  9. treeViewDown(new QTreeView(this)),
  10. model(new QStandardItemModel(this)),
  11. restoring(false),
  12. m_blockItemChanged(false)
  13. {
  14. if (!widget2) {
  15. // qWarning() << "DbTreeViewManager: widget2 未初始化";
  16. return;
  17. }
  18. // 设置模型
  19. treeViewDown->setModel(model);
  20. treeViewDown->setHeaderHidden(true);
  21. treeViewDown->setEditTriggers(QAbstractItemView::NoEditTriggers);
  22. // 设置树视图的几何位置
  23. treeViewDown->setGeometry(16, 106, widget2->width() - 16, widget2->height() - 106);
  24. // 安装事件过滤器以自定义绘制虚线
  25. treeViewDown->viewport()->installEventFilter(this);
  26. // 创建统一分隔线
  27. lineFrame1 = createUnifiedSeparator(widget2, 2);
  28. lineFrame1->setGeometry(16, 100, 460, 2);
  29. // 创建按钮并设置布局
  30. setupButton();
  31. // 创建导航栏
  32. navigationWidget = new QWidget(widget2);
  33. navigationWidget->setGeometry(15, 15, 300, 74);
  34. // 连接目录前的复选框信号与槽
  35. connect(model, &QStandardItemModel::itemChanged, this, &DbTreeViewManager::onItemChanged);
  36. // 目录树连接点击信号
  37. connect(treeViewDown, &QTreeView::clicked, this, &DbTreeViewManager::onTreeViewClicked);
  38. // 连接目录 expanded 和 collapsed 信号
  39. connect(treeViewDown, &QTreeView::expanded, this, [=](const QModelIndex &index) {
  40. QStandardItem *item = model->itemFromIndex(index);
  41. if (!item) return;
  42. QStringList path = buildItemPath(item);
  43. expandedPaths.insert(path.join("/"));
  44. updateSeparatorLine();
  45. // 保存展开路径
  46. saveExpandedPaths();
  47. });
  48. connect(treeViewDown, &QTreeView::collapsed, this, [=](const QModelIndex &index) {
  49. QStandardItem *item = model->itemFromIndex(index);
  50. if (!item) return;
  51. QStringList path = buildItemPath(item);
  52. expandedPaths.remove(path.join("/"));
  53. updateSeparatorLine();
  54. // 保存展开路径
  55. saveExpandedPaths();
  56. });
  57. // 所有展开操作完成后更新分隔线
  58. QTimer::singleShot(0, this, [=]() {
  59. QStandardItem *rootItem = model->invisibleRootItem();
  60. QStandardItem *thirdItem = findFirstThirdLevelItemDFS(rootItem);
  61. if (thirdItem) {
  62. QJsonObject thirdLevelObj = thirdItem->data(Qt::UserRole + 2).toJsonObject();
  63. if (thirdLevelObj.contains("IsThirdLevel") && thirdLevelObj["IsThirdLevel"].toBool()) {
  64. loadButtonConfigForThirdLevel(thirdLevelObj);
  65. }
  66. }
  67. });
  68. // 应用自定义只读复选框委托
  69. treeViewDown->setItemDelegate(new NonInteractiveCheckDelegate(treeViewDown));
  70. menuArray[0] = {2, false,-1};
  71. menuArray[1] = {5, false,-1};
  72. menuArray[2] = {3, false,-1};
  73. menuArray[3] = {4, false,-1};
  74. menuArray[4] = {6, false,-1};
  75. currentMenuId = -1;
  76. }
  77. DbTreeViewManager::~DbTreeViewManager()
  78. {
  79. }
  80. // 创建横线样式
  81. QFrame* DbTreeViewManager::createUnifiedSeparator(QWidget *parent, int height)
  82. {
  83. QFrame *separator = new QFrame(parent);
  84. separator->setFrameShape(QFrame::NoFrame); // 移除默认框架
  85. separator->setFixedHeight(height); // 设置固定高度
  86. separator->setStyleSheet("background-color: #C7CAEB;");
  87. separator->hide(); // 初始化为隐藏
  88. return separator;
  89. }
  90. // 目录树样式
  91. void DbTreeViewManager::applyCustomStyles() {
  92. treeViewDown->setStyleSheet(R"(
  93. /* 设置分支图标 */
  94. QTreeView::branch:closed:has-children {
  95. border-image: none;
  96. image: url(:/images/home_add.png);
  97. }
  98. QTreeView::branch:open:has-children {
  99. border-image: none;
  100. image: url(:/images/home_minus.png);
  101. }
  102. /* 设置多选框 */
  103. QTreeView::indicator:unchecked {
  104. image: url(:/images/home_NotSelecte.png);
  105. }
  106. QTreeView::indicator:checked {
  107. image: url(:/images/home_selected.png);
  108. }
  109. /* 背景透明,行间距 */
  110. QTreeView {
  111. background: transparent;
  112. border: none;
  113. }
  114. /* 设置项目选中的背景色 */
  115. QTreeView::item:selected {
  116. background-color: #A9B4FF;
  117. }
  118. /* 设置项目的行间距 */
  119. QTreeView::item {
  120. padding-top: 5px; /* 上边距 */
  121. padding-bottom: 5px; /* 下边距 */
  122. }
  123. )");
  124. }
  125. // 检查权限
  126. bool DbTreeViewManager::hasPrivilege(const int &UserGrade, const int &userPrivilege)
  127. {
  128. bool hasPriv;
  129. // UserGrade 是以逗号分隔的字符串,如 "1,2,3"
  130. if(UserGrade==userPrivilege){
  131. hasPriv = true;
  132. }else{
  133. hasPriv = false;
  134. }
  135. // qDebug() << "Checking privilege. UserGrade:" << UserGrade << "userPrivilege:" << userPrivilege << "result:" << hasPriv;
  136. return hasPriv;
  137. }
  138. void DbTreeViewManager::updateDb(const QString &TableName, const int &Id,const QString currentValue){
  139. QSqlDatabase db = QSqlDatabase::database();
  140. if (!db.isOpen()) {
  141. qWarning() << "数据库未打开";
  142. }
  143. QString sql = QString("UPDATE %1 SET currentValue = :newValue WHERE id = :id").arg(TableName);
  144. QSqlQuery query;
  145. query.prepare(sql);
  146. query.bindValue(":newValue", currentValue);
  147. query.bindValue(":id", Id);
  148. // 执行更新操作
  149. if (!query.exec()) {
  150. qWarning() << "Failed to update currentValue:" << query.lastError().text();
  151. } else {
  152. qDebug() << "currentValue updated successfully.";
  153. }
  154. }
  155. void DbTreeViewManager::initializeTree(int configId, const int &userPrivilege)
  156. {
  157. qDebug() << "Initializing tree with configId:" << configId << "and userPrivilege:" << userPrivilege;
  158. m_currentConfigId = configId; // 设置当前配置ID
  159. // 先清空历史
  160. clearHistory();
  161. // 保存之前的选中/展开状态
  162. m_blockItemChanged = true;
  163. restoring = true;
  164. // 清理当前的分隔线
  165. clearAllSeparators();
  166. // 清空已有模型数据和相关记录
  167. model->clear();
  168. firstLevelSeparators.clear();
  169. expandedPaths.clear();
  170. // 清理并隐藏三级目录窗口
  171. clearThirdLevelMenu();
  172. // **Home 界面逻辑**
  173. if (configId == 1) {
  174. // 隐藏目录树和分隔线
  175. treeViewDown->hide();
  176. for (auto separator : firstLevelSeparators) {
  177. if (separator)
  178. separator->hide();
  179. }
  180. // 隐藏导航栏
  181. navigationWidget->hide();
  182. // 隐藏按钮
  183. updateButtonsVisibility(); // 将按钮隐藏
  184. // 隐藏特定的分隔线 lineFrame1
  185. if (lineFrame1) {
  186. lineFrame1->hide();
  187. }
  188. // 从 BondHead 和 Buttons 表中加载 DirectoryId = 1 的数据
  189. QJsonObject data = fetchThirdLevelData(1, userPrivilege);
  190. displayThirdLevelFields(data, true); // 传递参数表示 Home 界面
  191. // 把当前页面压到 m_backStack 里
  192. PageState st;
  193. st.path << "Home";
  194. st.isThirdLevel = true;
  195. st.directoryId = 1;
  196. m_backStack.append(st);
  197. if(m_backStack.size() >= 2){
  198. buttonLeft->setIcon(QIcon(":/images/home_left.png"));
  199. }
  200. } else {
  201. // **其他配置逻辑**
  202. // 设置 treeViewDown 的几何位置
  203. treeViewDown->setGeometry(16, 106, widget2->width() - 16, widget2->height() - 106);
  204. // 显示目录树和分隔线
  205. treeViewDown->show();
  206. for (auto separator : firstLevelSeparators) {
  207. if (separator)
  208. separator->show();
  209. }
  210. // 应用自定义样式
  211. applyCustomStyles();
  212. // 显示导航栏
  213. navigationWidget->show();
  214. // 显示按钮
  215. updateButtonsVisibility();
  216. // 显示特定的分隔线 lineFrame1
  217. if (lineFrame1) {
  218. lineFrame1->show();
  219. }
  220. // 加载目录数据 并进行权限判断
  221. loadDirectories(configId, userPrivilege);
  222. // 更新分隔线
  223. updateSeparatorLine();
  224. m_blockItemChanged = false;
  225. restoring = false;
  226. // qDebug() << "Tree initialization completed.";
  227. // 恢复展开路径
  228. loadExpandedPaths();
  229. // 恢复复选框状态
  230. loadCheckedPaths();
  231. // 自动选中第一个根目录项并更新导航栏
  232. QStandardItem *rootItem = model->invisibleRootItem()->child(0);
  233. if (rootItem) {
  234. QModelIndex rootIndex = model->indexFromItem(rootItem);
  235. treeViewDown->setCurrentIndex(rootIndex);
  236. updateNavigationBar(rootIndex);
  237. // 如果当前根目录是三级目录,则加载其字段内容
  238. QVariant dataVar = rootItem->data(Qt::UserRole + 2).toJsonObject();
  239. bool isThirdLevel = false;
  240. int directoryId = -1;
  241. if (dataVar.canConvert<QJsonObject>()) {
  242. QJsonObject thirdLevelObj = dataVar.toJsonObject();
  243. if (thirdLevelObj.contains("IsThirdLevel") && thirdLevelObj["IsThirdLevel"].toBool()) {
  244. isThirdLevel = true;
  245. if (thirdLevelObj.contains("Id")) {
  246. directoryId = thirdLevelObj["Id"].toInt();
  247. }
  248. }
  249. }
  250. if (isThirdLevel) {
  251. if (directoryId == -1) {
  252. // qWarning() << "无效的 DirectoryId,无法加载第三层目录内容。";
  253. return;
  254. }
  255. // userPrivilege 同样传递
  256. QJsonObject data = fetchThirdLevelData(directoryId, userPrivilege);
  257. displayThirdLevelFields(data, false); // 传递参数表示非 Home 界面
  258. // 把当前状态压入 m_backStack
  259. PageState st;
  260. st.path = buildItemPath(rootItem);
  261. st.isThirdLevel = true;
  262. st.directoryId = directoryId;
  263. m_backStack.append(st);
  264. if(m_backStack.size() >= 2){
  265. buttonLeft->setIcon(QIcon(":/images/home_left.png"));
  266. }
  267. }
  268. } else {
  269. // qWarning() << "树形模型中没有根目录项。";
  270. }
  271. // 自动找第一个三级目录
  272. QStandardItem *rootItem1 = model->invisibleRootItem();
  273. QStandardItem *firstThirdItem = findFirstThirdLevelItemDFS(rootItem1);
  274. if (!firstThirdItem) {
  275. // qDebug() << "[initializeTree] No third-level item found, do nothing.";
  276. return;
  277. }
  278. // QStandardItem 里获取它的目录信息
  279. QVariant dataVar = firstThirdItem->data(Qt::UserRole + 2);
  280. if (!dataVar.canConvert<QJsonObject>()) {
  281. // qWarning() << "[initializeTree] firstThirdItem->data 无法转换为 QJsonObject";
  282. return;
  283. }
  284. QJsonObject dirObj = dataVar.toJsonObject();
  285. if (!dirObj.contains("Id")) {
  286. // qWarning() << "[initializeTree] 第一个三级目录无 Id 字段,无法加载";
  287. return;
  288. }
  289. int directoryId = dirObj["Id"].toInt();
  290. // 数据库BondHead/Buttons
  291. QJsonObject data = fetchThirdLevelData(directoryId, userPrivilege);
  292. if (!data.contains("buttons")) {
  293. // 第三层没有 buttons 字段
  294. qWarning() << "[initializeTree] fetchThirdLevelData: no 'buttons', skip";
  295. return;
  296. }
  297. // singleShot 在所有展开操作完成后更新分隔线
  298. QTimer::singleShot(0, this, &DbTreeViewManager::updateSeparatorLine);
  299. // loadButtonConfigForThirdLevel 显示按钮
  300. loadButtonConfigForThirdLevel(data);
  301. }
  302. }
  303. // 从数据库加载目录 包含权限判断
  304. void DbTreeViewManager::loadDirectories(int configId, const int &userPrivilege)
  305. {
  306. // qDebug() << "Loading directories for configId:" << configId << "with userPrivilege:" << userPrivilege;
  307. QSqlDatabase db = QSqlDatabase::database();
  308. if (!db.isOpen()) {
  309. qWarning() << "数据库未打开";
  310. return;
  311. }
  312. QSqlQuery query(db);
  313. query.prepare(R"(
  314. SELECT Id, Name, ParentId, IsThirdLevel, Separator, UserGrade, Circle
  315. FROM Directories
  316. WHERE ConfigId = :configId
  317. )");
  318. query.bindValue(":configId", configId);
  319. if (!query.exec()) {
  320. qWarning() << "查询 Directories 失败:" << query.lastError().text();
  321. return;
  322. }
  323. // 以 QJsonObject 保存所有目录
  324. QList<QJsonObject> directories;
  325. while (query.next()) {
  326. QJsonObject obj;
  327. int id = query.value("Id").toInt();
  328. obj["Id"] = id;
  329. obj["Name"] = query.value("Name").toString();
  330. obj["ParentId"] = query.value("ParentId").isNull() ? -1 : query.value("ParentId").toInt();
  331. obj["IsThirdLevel"] = query.value("IsThirdLevel").toBool();
  332. obj["Separator"] = query.value("Separator").toInt();
  333. obj["UserGrade"] = query.value("UserGrade").toString();
  334. obj["Circle"] = query.value("Circle").toInt();
  335. qDebug() << "加载目录:"<< obj["Name"].toString() << " ParentId:" << obj["ParentId"].toInt()<< " Separator:" << obj["Separator"].toInt();
  336. qDebug() << " Circle:" << obj["Circle"].toInt();
  337. // 权限判断:只有当记录的 UserGrade 中包含当前用户权限时才加入
  338. bool ok;
  339. if (hasPrivilege(obj["UserGrade"].toString().toInt(&ok,16), userPrivilege))
  340. directories.append(obj);
  341. else
  342. qDebug() << "目录跳过(权限不足):" << obj["Name"].toString();
  343. }
  344. // qDebug() << "Loaded directories count:" << directories.size();
  345. // 根据目录列表构建树模型
  346. buildTreeFromDirectories(directories);
  347. }
  348. void DbTreeViewManager::buildTreeFromDirectories(const QList<QJsonObject> &directories)
  349. {
  350. // 建立 Id->QStandardItem 的映射
  351. QMap<int, QStandardItem*> idItemMap;
  352. for (const QJsonObject &dir : directories) {
  353. QStandardItem *item = new QStandardItem(dir["Name"].toString());
  354. item->setData(dir["Id"].toInt(), Qt::UserRole + 1); // 保存目录Id
  355. // 如果是三级目录,将整个 JSON 对象存到 UserRole+2
  356. if (dir["IsThirdLevel"].toBool()) {
  357. item->setData(dir, Qt::UserRole + 2);
  358. } else {
  359. item->setData(false, Qt::UserRole + 2); // 标记为非三级目录
  360. }
  361. item->setCheckable(true);
  362. // 复选框状态由程序逻辑设置
  363. item->setCheckState(Qt::Unchecked);
  364. idItemMap.insert(dir["Id"].toInt(), item);
  365. }
  366. // 建立父子关系
  367. for (const QJsonObject &dir : directories) {
  368. int parentId = dir["ParentId"].toInt();
  369. int currentId = dir["Id"].toInt();
  370. QStandardItem *childItem = idItemMap.value(currentId);
  371. if (parentId == -1) {
  372. // 说明这是一级目录
  373. model->invisibleRootItem()->appendRow(childItem);
  374. // 如果一级目录的 "Separator" == 1,则为其创建一条分割线
  375. if (dir["Separator"].toInt() == 1) {
  376. QFrame *sep = createUnifiedSeparator(widget2, 2);
  377. sep->hide();
  378. firstLevelSeparators.insert(childItem, sep);
  379. }
  380. } else {
  381. // 非一级目录 => 子目录
  382. QStandardItem *parentItem = idItemMap.value(parentId);
  383. if (parentItem)
  384. parentItem->appendRow(childItem);
  385. else
  386. qWarning() << "无法找到 ParentId:" << parentId << "的父目录项";
  387. }
  388. }
  389. }
  390. // 查询三级目录下的 BondHead 和 Buttons 数据 均判断权限
  391. QJsonObject DbTreeViewManager::fetchThirdLevelData(int directoryId, const int &userPrivilege)
  392. {
  393. QJsonObject data;
  394. QJsonArray fieldsArray;
  395. QJsonArray buttonsArray;
  396. QString temp;
  397. bool allChangeFlag = true; // 默认所有 ChangeFlag 为 true
  398. QSqlDatabase db = QSqlDatabase::database();
  399. if (!db.isOpen()) {
  400. qWarning() << "数据库未打开";
  401. return data;
  402. }
  403. // 查询 TableName 表
  404. QSqlQuery queryBondtest(db);
  405. queryBondtest.prepare(R"(
  406. SELECT TableName
  407. FROM Directories
  408. WHERE Id = :dirId
  409. )");
  410. queryBondtest.bindValue(":dirId",directoryId);
  411. if (queryBondtest.exec()) {
  412. while (queryBondtest.next()) {
  413. temp = queryBondtest.value("TableName").toString();
  414. }
  415. }
  416. QStringList tableName = temp.split(",");
  417. QString currentTableName;
  418. for (const QString &item : tableName) {
  419. if (item.isEmpty()) {
  420. qDebug() << "Encountered an empty string, stopping traversal.";
  421. break; // 遇到空字符串时退出循环
  422. }else{
  423. currentTableName = item;
  424. QString sql = QString("SELECT Id, DirectoryId, Describe, Type, Value,CurrentValue,UpLimit,DownLimit,units, Groupld, UserGrade, ChangeFlag FROM %1 WHERE DirectoryId = :dirId").arg(currentTableName);
  425. // 查询 BondHead 表
  426. QSqlQuery queryBond(db);
  427. queryBond.prepare(sql);
  428. queryBond.bindValue(":dirId", directoryId);
  429. if (queryBond.exec()) {
  430. while (queryBond.next()) {
  431. bool ok;
  432. int dbUserGrade = queryBond.value("UserGrade").toString().toInt(&ok, 16);
  433. // 只有当数据库记录的 UserGrade 包含当前用户权限时才加载该字段
  434. if (!hasPrivilege(dbUserGrade, userPrivilege))
  435. continue;
  436. QJsonObject field;
  437. field["Id"] = queryBond.value("Id").toInt();
  438. field["DirectoryId"] = queryBond.value("DirectoryId").toInt();
  439. field["Describe"] = queryBond.value("Describe").toString();
  440. field["Type"] = queryBond.value("Type").toString();
  441. field["Value"] = queryBond.value("Value").toString();
  442. field["CurrentValue"] = queryBond.value("CurrentValue").toString();
  443. field["UpLimit"] = queryBond.value("UpLimit").toString();
  444. field["DownLimit"] = queryBond.value("DownLimit").toString();
  445. field["units"] = queryBond.value("units").toString();
  446. field["Groupld"] = queryBond.value("Groupld").toInt();
  447. field["ChangeFlag"] = queryBond.value("ChangeFlag").toInt();
  448. field["TableName"] = currentTableName;
  449. fieldsArray.append(field);
  450. // 如果有任一字段 ChangeFlag 为 0,则 allChangeFlag = false
  451. if (queryBond.value("ChangeFlag").toInt() == 0)
  452. allChangeFlag = false;
  453. }
  454. // qDebug() << "Fetched fields:" << fieldsArray;
  455. } else {
  456. qWarning() << "查询 BondHead 失败:" << queryBond.lastError().text();
  457. }
  458. }
  459. }
  460. //QString sql = QString("SELECT Id, DirectoryId, Describe, Type, Value,units, Groupld, UserGrade, ChangeFlag FROM %1 WHERE DirectoryId = :dirId").arg(currentTableName);
  461. // // 查询 BondHead 表
  462. // QSqlQuery queryBond(db);
  463. // queryBond.prepare(sql);
  464. // queryBond.bindValue(":dirId", directoryId);
  465. // if (queryBond.exec()) {
  466. // while (queryBond.next()) {
  467. // bool ok;
  468. // int dbUserGrade = queryBond.value("UserGrade").toString().toInt(&ok, 16);
  469. // // 只有当数据库记录的 UserGrade 包含当前用户权限时才加载该字段
  470. // if (!hasPrivilege(dbUserGrade, userPrivilege))
  471. // continue;
  472. // QJsonObject field;
  473. // field["Id"] = queryBond.value("Id").toInt();
  474. // field["DirectoryId"] = queryBond.value("DirectoryId").toInt();
  475. // field["Describe"] = queryBond.value("Describe").toString();
  476. // field["Type"] = queryBond.value("Type").toString();
  477. // field["Value"] = queryBond.value("Value").toString();
  478. // field["units"] = queryBond.value("units").toString();
  479. // field["Groupld"] = queryBond.value("Groupld").toInt();
  480. // field["ChangeFlag"] = queryBond.value("ChangeFlag").toInt();
  481. // fieldsArray.append(field);
  482. // // 如果有任一字段 ChangeFlag 为 0,则 allChangeFlag = false
  483. // if (queryBond.value("ChangeFlag").toInt() == 0)
  484. // allChangeFlag = false;
  485. // }
  486. // // qDebug() << "Fetched fields:" << fieldsArray;
  487. // } else {
  488. // qWarning() << "查询 BondHead 失败:" << queryBond.lastError().text();
  489. // }
  490. // 查询 Buttons 表
  491. QSqlQuery queryBtn(db);
  492. queryBtn.prepare(R"(
  493. SELECT ButtonId, Icon, Text, Enabled, UserGrade
  494. FROM Buttons
  495. WHERE DirectoryId = :dirId
  496. )");
  497. queryBtn.bindValue(":dirId", directoryId);
  498. if (queryBtn.exec()) {
  499. while (queryBtn.next()) {
  500. bool ok;
  501. int btnUserGrade = queryBtn.value("UserGrade").toString().toInt(&ok, 16);
  502. if (!hasPrivilege(btnUserGrade, userPrivilege))
  503. continue;
  504. QJsonObject button;
  505. button["id"] = queryBtn.value("ButtonId").toString();
  506. button["icon"] = queryBtn.value("Icon").toString();
  507. button["text"] = queryBtn.value("Text").toString();
  508. button["enabled"] = queryBtn.value("Enabled").toBool();
  509. buttonsArray.append(button);
  510. }
  511. // qDebug() << "Fetched buttons:" << buttonsArray;
  512. } else {
  513. qWarning() << "查询 Buttons 失败:" << queryBtn.lastError().text();
  514. }
  515. data["fields"] = fieldsArray;
  516. data["buttons"] = buttonsArray;
  517. data["IsThirdLevel"] = true;
  518. data["allChangeFlag"] = allChangeFlag;
  519. return data;
  520. }
  521. // 事件过滤器,用于自定义绘制虚线
  522. bool DbTreeViewManager::eventFilter(QObject *watched, QEvent *event)
  523. {
  524. // 拦截 Paint 事件
  525. if (watched == treeViewDown->viewport() && event->type() == QEvent::Paint)
  526. {
  527. // 进行默认绘制
  528. bool handled = QWidget::eventFilter(watched, event);
  529. // 使用 QPainter 叠加画“拐角线”
  530. QPainter painter(treeViewDown->viewport());
  531. if (!painter.isActive()) {
  532. qWarning() << "Painter not active";
  533. return handled;
  534. }
  535. painter.save();
  536. painter.setPen(QPen(Qt::gray, 1, Qt::DashLine)); // 灰色、1px 宽、虚线
  537. // 调用递归函数,绘制所有分支
  538. paintAllBranches(QModelIndex(), painter);
  539. painter.restore();
  540. return handled;
  541. }
  542. // 其余事件交给父类默认处理
  543. return QWidget::eventFilter(watched, event);
  544. }
  545. // 递归绘制所有分支
  546. void DbTreeViewManager::paintAllBranches(const QModelIndex &parentIndex, QPainter &painter)
  547. {
  548. int rowCount = model->rowCount(parentIndex);
  549. for(int i = 0; i < rowCount; ++i)
  550. {
  551. // 当前子节点
  552. QModelIndex childIndex = model->index(i, 0, parentIndex);
  553. if (!childIndex.isValid()) continue;
  554. // 1) 父->子拐角线
  555. drawParentChildLine(childIndex, painter);
  556. // 2) 兄弟延续竖线(如果本节点不是最后一个兄弟,就在拐点列画条向下的线)
  557. if (i < rowCount - 1) {
  558. drawSiblingLine(childIndex, painter);
  559. }
  560. // 3) 递归处理子节点
  561. paintAllBranches(childIndex, painter);
  562. }
  563. }
  564. // 在“父节点 -> 子节点”间画一条“L”型拐角线,调整横向线段的长度
  565. void DbTreeViewManager::drawParentChildLine(const QModelIndex &childIndex, QPainter &painter)
  566. {
  567. QModelIndex parentIndex = childIndex.parent();
  568. if (!parentIndex.isValid()) {
  569. // “顶层节点”定义一个固定的起点 (rootX, rootY)
  570. int indent = treeViewDown->indentation();
  571. int depth = 0; // 顶层节点深度为0
  572. int branchX = (depth + 1) * indent - indent / 2; // 计算 branchX 基于缩进和深度
  573. // 定义 rootY 为节点中心 Y
  574. QRect childRect = treeViewDown->visualRect(childIndex);
  575. if (!childRect.isValid())
  576. return;
  577. int rootY = childRect.center().y();
  578. // 定义横向偏移量
  579. const int hOffset = -20;
  580. // 绘制竖线
  581. painter.drawLine(QPoint(branchX, rootY),
  582. QPoint(branchX, childRect.center().y()));
  583. // 计算新的横线终点
  584. int newX = childRect.left() + hOffset;
  585. // 绘制横线
  586. painter.drawLine(QPoint(branchX, childRect.center().y()),
  587. QPoint(newX, childRect.center().y()));
  588. return;
  589. }
  590. QRect parentRect = treeViewDown->visualRect(parentIndex);
  591. QRect childRect = treeViewDown->visualRect(childIndex);
  592. if (!parentRect.isValid() || !childRect.isValid()) {
  593. // 父或子超出可视区域
  594. return;
  595. }
  596. int pMidY = parentRect.center().y();
  597. int cMidY = childRect.center().y();
  598. // 计算节点深度
  599. int depth = 0;
  600. QModelIndex p = parentIndex;
  601. while (p.isValid()) {
  602. depth++;
  603. p = p.parent();
  604. }
  605. int indent = treeViewDown->indentation();
  606. int branchX = depth * indent - indent / 2;
  607. // branchX 不超出视图范围
  608. branchX = std::max(branchX, 0);
  609. // 定义横向偏移量
  610. const int hOffset = -15;
  611. // 绘制竖线
  612. painter.drawLine(QPoint(branchX, pMidY), QPoint(branchX, cMidY));
  613. // 计算新的横线终点
  614. int newX = childRect.left() + hOffset;
  615. // 绘制横线
  616. painter.drawLine(QPoint(branchX, cMidY), QPoint(newX, cMidY));
  617. }
  618. // 节点下面还有兄弟,则在拐点列那里继续往下画竖线
  619. void DbTreeViewManager::drawSiblingLine(const QModelIndex &childIndex, QPainter &painter)
  620. {
  621. QModelIndex parentIndex = childIndex.parent();
  622. if (!parentIndex.isValid()) {
  623. return; // 没有父节点
  624. }
  625. // 下一个兄弟
  626. int row = childIndex.row();
  627. int lastRow = model->rowCount(parentIndex) - 1;
  628. if (row >= lastRow) {
  629. return; // 说明是最后一个兄弟,不用画延伸线
  630. }
  631. QModelIndex nextSibling = model->index(row + 1, 0, parentIndex);
  632. QRect currRect = treeViewDown->visualRect(childIndex);
  633. QRect nextRect = treeViewDown->visualRect(nextSibling);
  634. if (!currRect.isValid() || !nextRect.isValid()) {
  635. return;
  636. }
  637. // 计算节点深度
  638. int depth = 0;
  639. QModelIndex p = parentIndex;
  640. while (p.isValid()) {
  641. depth++;
  642. p = p.parent();
  643. }
  644. int indent = treeViewDown->indentation();
  645. int branchX = depth * indent - indent / 2;
  646. // 确保 branchX 不超出视图范围
  647. branchX = std::max(branchX, 0);
  648. // 从当前节点底部向下延伸到下一个兄弟节点顶部
  649. int startY = currRect.bottom();
  650. int endY = nextRect.top();
  651. painter.drawLine(QPoint(branchX, startY), QPoint(branchX, endY));
  652. }
  653. // 递归查找第一个三级目录项
  654. QStandardItem* DbTreeViewManager::findFirstThirdLevelItemDFS(QStandardItem *parentItem)
  655. {
  656. if (!parentItem) {
  657. return nullptr;
  658. }
  659. // 遍历当前 parentItem 的所有子
  660. for (int i = 0; i < parentItem->rowCount(); ++i) {
  661. QStandardItem *child = parentItem->child(i);
  662. if (!child) continue;
  663. // 检查这个子节点是否是三级目录
  664. QVariant data = child->data(Qt::UserRole + 2);
  665. if (data.canConvert<QJsonObject>()) {
  666. QJsonObject obj = data.toJsonObject();
  667. if (obj.contains("IsThirdLevel") && obj["IsThirdLevel"].toBool()) {
  668. // 找到第一个 IsThirdLevel = true 的节点就返回
  669. return child;
  670. }
  671. }
  672. // 如果不是 IsThirdLevel,继续往子节点里找
  673. QStandardItem* deeperFound = findFirstThirdLevelItemDFS(child);
  674. if (deeperFound) {
  675. return deeperFound;
  676. }
  677. }
  678. return nullptr;
  679. }
  680. void DbTreeViewManager::onItemChanged(QStandardItem *item)
  681. {
  682. if (m_blockItemChanged || restoring) {
  683. return; // 防止递归和恢复期间触发
  684. }
  685. m_blockItemChanged = true;
  686. Qt::CheckState state = item->checkState();
  687. // 更新所有子项的复选框状态
  688. for (int i = 0; i < item->rowCount(); ++i) {
  689. QStandardItem *child = item->child(i);
  690. if (child) {
  691. child->setCheckState(state);
  692. // 递归更新子项
  693. onItemChanged(child);
  694. }
  695. }
  696. // 更新所有父项的复选框状态
  697. QModelIndex parentIndex = item->index().parent();
  698. while (parentIndex.isValid()) {
  699. QStandardItem *parentItem = model->itemFromIndex(parentIndex);
  700. if (!parentItem) break;
  701. int checkedCount = 0;
  702. int totalCount = parentItem->rowCount();
  703. for (int i = 0; i < totalCount; ++i) {
  704. QStandardItem *child = parentItem->child(i);
  705. if (child && child->checkState() == Qt::Checked) {
  706. checkedCount++;
  707. }
  708. }
  709. if (checkedCount == totalCount) {
  710. parentItem->setCheckState(Qt::Checked);
  711. }
  712. else {
  713. parentItem->setCheckState(Qt::Unchecked);
  714. }
  715. parentIndex = parentIndex.parent();
  716. }
  717. m_blockItemChanged = false;
  718. // 记录复选框状态
  719. saveCheckedPaths();
  720. }
  721. // 初始化和设置按钮
  722. void DbTreeViewManager::setupButton()
  723. {
  724. // 创建按钮并设置属性
  725. auto createButton = [&](QPushButton*& button, const QString& iconPath, const QRect& geometry) {
  726. button = new QPushButton(this);
  727. button->setIcon(QIcon(iconPath));
  728. button->setGeometry(geometry);
  729. button->setStyleSheet(R"(
  730. QPushButton {
  731. position: absolute;
  732. border-radius: 6px;
  733. opacity: 1;
  734. background: #FFFFFF;
  735. border: 1px solid #BABBDC;
  736. }
  737. QPushButton:hover {
  738. background-color: #A9B4FF; /* 鼠标悬停效果 */
  739. }
  740. )");
  741. button->show();
  742. };
  743. // 根据原始代码调整按钮的位置和大小
  744. createButton(ButtonBack, ":/images/home_openFile.png", QRect(328, 6, 76, 30));
  745. createButton(buttonUp, ":/images/home_up.png", QRect(408, 6, 36, 30));
  746. createButton(buttonDown, ":/images/home_down.png", QRect(408, 40, 36, 30));
  747. createButton(buttonLeft, ":/images/home_left_hide.png", QRect(328, 40, 36, 30));
  748. createButton(buttonRight, ":/images/home_right.png", QRect(368, 40, 36, 30));
  749. // 连接按钮的点击信号到相应的槽函数
  750. connect(ButtonBack, &QPushButton::clicked, this, &DbTreeViewManager::onButtonBackClicked);
  751. connect(buttonUp, &QPushButton::clicked, this, &DbTreeViewManager::onButtonUpClicked);
  752. connect(buttonDown, &QPushButton::clicked, this, &DbTreeViewManager::onButtonDownClicked);
  753. connect(buttonLeft, &QPushButton::clicked, this, &DbTreeViewManager::onButtonLeftClicked);
  754. connect(buttonRight, &QPushButton::clicked, this, &DbTreeViewManager::onButtonRightClicked);
  755. }
  756. void DbTreeViewManager::updateButtonsVisibility()
  757. {
  758. if (m_currentConfigId == 1) {
  759. // Home 界面,隐藏所有按钮
  760. ButtonBack->hide();
  761. buttonUp->hide();
  762. buttonDown->hide();
  763. buttonLeft->hide();
  764. buttonRight->hide();
  765. }
  766. else {
  767. // 其他配置,显示所有按钮
  768. ButtonBack->show();
  769. buttonUp->show();
  770. buttonDown->show();
  771. buttonLeft->show();
  772. buttonRight->show();
  773. }
  774. }
  775. QStandardItem* DbTreeViewManager::deepCopyItem(const QStandardItem *item){
  776. if (!item) {
  777. return nullptr;
  778. }
  779. // 创建一个新的 QStandardItem
  780. QStandardItem *newItem = new QStandardItem(item->text());
  781. newItem->setIcon(item->icon());
  782. newItem->setToolTip(item->toolTip());
  783. newItem->setEditable(item->isEditable());
  784. newItem->setCheckable(item->isCheckable());
  785. newItem->setCheckState(item->checkState());
  786. // 递归复制子项
  787. for (int i = 0; i < item->rowCount(); ++i) {
  788. QStandardItem *childItem = item->child(i);
  789. QStandardItem *newChildItem = deepCopyItem(childItem);
  790. newItem->appendRow(newChildItem);
  791. }
  792. return newItem;
  793. }
  794. void DbTreeViewManager::loadpage(const int &configId){
  795. for(int i=0;i<5;i++){
  796. if(configId == menuArray[i].menuId){
  797. QJsonObject data = fetchThirdLevelData(menuArray[i].index, 0x1);
  798. displayThirdLevelFields(data, false);
  799. }
  800. }
  801. }
  802. void DbTreeViewManager::onTreeViewClicked(const QModelIndex &index)
  803. {
  804. QStandardItem *item = model->itemFromIndex(index);
  805. if (!item) return;
  806. // 是否第三层
  807. bool isThird = false;
  808. int dirId = -1;
  809. QVariant dataVar = item->data(Qt::UserRole + 2);
  810. if (dataVar.canConvert<QJsonObject>()) {
  811. QJsonObject obj = dataVar.toJsonObject();
  812. if (obj.contains("IsThirdLevel") && obj["IsThirdLevel"].toBool()) {
  813. isThird = true;
  814. if (obj.contains("Id")) {
  815. dirId = obj["Id"].toInt();
  816. }
  817. }
  818. }
  819. updateNavigationBar(index);
  820. if (isThird) {
  821. int userPrivilege = 0x1; // 示例
  822. if (dirId < 0) {
  823. qWarning() << "无效directoryId";
  824. return;
  825. }
  826. QJsonObject data = fetchThirdLevelData(dirId, userPrivilege);
  827. displayThirdLevelFields(data, false);
  828. for(int i=0;i<5;i++){
  829. if(currentMenuId == menuArray[i].menuId){
  830. menuArray[i].isthird = true;
  831. menuArray[i].index = dirId;
  832. }
  833. }
  834. // 将“新页面”压入后退栈, 并清空前进栈
  835. PageState st;
  836. st.path = buildItemPath(item);
  837. st.isThirdLevel = true;
  838. st.directoryId = dirId;
  839. m_backStack.append(st);
  840. if(m_backStack.size() >= 2){
  841. buttonLeft->setIcon(QIcon(":/images/home_left.png"));
  842. }
  843. m_forwardStack.clear();
  844. buttonRight->setIcon(QIcon(":/images/home_right.png"));
  845. } else {
  846. // 不是第三层,只是选中目录
  847. // 清理第三层窗口
  848. if (m_thirdLevelFieldWnd) {
  849. m_thirdLevelFieldWnd->close();
  850. m_thirdLevelFieldWnd->deleteLater();
  851. m_thirdLevelFieldWnd = nullptr;
  852. }
  853. // 同样更新历史
  854. PageState st;
  855. st.path = buildItemPath(item);
  856. st.isThirdLevel = false;
  857. st.directoryId = -1;
  858. m_backStack.append(st);
  859. if(m_backStack.size() >= 2){
  860. buttonLeft->setIcon(QIcon(":/images/home_left.png"));
  861. }
  862. m_forwardStack.clear();
  863. buttonRight->setIcon(QIcon(":/images/home_right.png"));
  864. }
  865. }
  866. void DbTreeViewManager::onTreeViewClicked_updown(const QModelIndex &index){
  867. QStandardItem *item = model->itemFromIndex(index);
  868. if (!item) return;
  869. // 是否第三层
  870. bool isThird = false;
  871. int dirId = -1;
  872. QVariant dataVar = item->data(Qt::UserRole + 2);
  873. if (dataVar.canConvert<QJsonObject>()) {
  874. QJsonObject obj = dataVar.toJsonObject();
  875. if (obj.contains("IsThirdLevel") && obj["IsThirdLevel"].toBool()) {
  876. isThird = true;
  877. if (obj.contains("Id")) {
  878. dirId = obj["Id"].toInt();
  879. }
  880. }
  881. }
  882. updateNavigationBar(index);
  883. if (isThird) {
  884. int userPrivilege = 0x1; // 示例
  885. if (dirId < 0) {
  886. qWarning() << "无效directoryId";
  887. return;
  888. }
  889. QJsonObject data = fetchThirdLevelData(dirId, userPrivilege);
  890. displayThirdLevelFields(data, false);
  891. // 将“新页面”压入后退栈, 并清空前进栈
  892. PageState st;
  893. st.path = buildItemPath(item);
  894. st.isThirdLevel = true;
  895. st.directoryId = dirId;
  896. m_backStack.append(st);
  897. if(m_backStack.size() >= 2){
  898. buttonLeft->setIcon(QIcon(":/images/home_left.png"));
  899. }
  900. m_forwardStack.clear();
  901. buttonRight->setIcon(QIcon(":/images/home_right.png"));
  902. } else {
  903. // 不是第三层,只是选中目录
  904. // 清理第三层窗口
  905. if (m_thirdLevelFieldWnd) {
  906. m_thirdLevelFieldWnd->close();
  907. m_thirdLevelFieldWnd->deleteLater();
  908. m_thirdLevelFieldWnd = nullptr;
  909. }
  910. // 同样更新历史
  911. PageState st;
  912. st.path = buildItemPath(item);
  913. st.isThirdLevel = false;
  914. st.directoryId = -1;
  915. m_backStack.append(st);
  916. if(m_backStack.size() >= 2){
  917. buttonLeft->setIcon(QIcon(":/images/home_left.png"));
  918. }
  919. m_forwardStack.clear();
  920. buttonRight->setIcon(QIcon(":/images/home_right.png"));
  921. }
  922. }
  923. void DbTreeViewManager::updateNavigationBar(const QModelIndex &index)
  924. {
  925. QStandardItem *item = model->itemFromIndex(index);
  926. if (!item) {
  927. qWarning() << "导航栏更新失败:未找到对应项";
  928. return;
  929. }
  930. // 清理现有布局
  931. if (navigationWidget->layout()) {
  932. QLayoutItem *child;
  933. while ((child = navigationWidget->layout()->takeAt(0)) != nullptr) {
  934. if (child->widget()) {
  935. child->widget()->deleteLater();
  936. }
  937. delete child;
  938. }
  939. delete navigationWidget->layout();
  940. }
  941. // 构建路径列表,从当前项回溯到根节点
  942. QList<QStandardItem *> path;
  943. QStandardItem *temp = item;
  944. while (temp) {
  945. path.prepend(temp); // 从根节点开始
  946. temp = temp->parent();
  947. }
  948. QVBoxLayout *newLayout = new QVBoxLayout; // 创建新的导航栏布局
  949. newLayout->setContentsMargins(0, 0, 3, 3);
  950. newLayout->setSpacing(0);
  951. // 确保显示三行
  952. for (int i = 0; i < 3; ++i) {
  953. QLabel *label = new QLabel;
  954. if (i < path.size()) {
  955. QString text = path[i]->text();
  956. if (i == 1) text = " " + text; // 二级目录缩进
  957. if (i == 2) text = " " + text; // 三级目录缩进
  958. label->setText(text);
  959. } else {
  960. label->setText(""); // 填充空白行
  961. }
  962. QFont font = label->font(); // 设置字体和样式
  963. font.setPointSize(14);
  964. font.setFamily("思源黑体");
  965. font.setBold(true); // 设置文字为粗体
  966. font.setLetterSpacing(QFont::PercentageSpacing,105); // 设置字间距100%为默认
  967. label->setFont(font);
  968. label->setFixedHeight(navigationWidget->height() / 3);
  969. newLayout->addWidget(label);
  970. }
  971. // 设置布局并更新导航栏
  972. navigationWidget->setLayout(newLayout);
  973. navigationWidget->update();
  974. }
  975. void DbTreeViewManager::clearAllSeparators()
  976. {
  977. // 遍历 firstLevelSeparators 中所有 QFrame,
  978. // 隐藏后调用 deleteLater()
  979. for (auto separator : firstLevelSeparators.values()) {
  980. if(separator) {
  981. separator->hide();
  982. separator->deleteLater();
  983. }
  984. }
  985. // 清空映射
  986. firstLevelSeparators.clear();
  987. }
  988. void DbTreeViewManager::updateSeparatorLine()
  989. {
  990. // 如果目录树被隐藏,就把分割线都藏起来
  991. if (!treeViewDown->isVisible()) {
  992. for (auto it = firstLevelSeparators.begin(); it != firstLevelSeparators.end(); ++it) {
  993. QFrame *sep = it.value();
  994. if (sep) sep->hide();
  995. }
  996. return;
  997. }
  998. // 遍历所有“一级目录”与其分隔线
  999. for (auto it = firstLevelSeparators.begin(); it != firstLevelSeparators.end(); ++it) {
  1000. QStandardItem *firstLevelItem = it.key();
  1001. QFrame *separator = it.value();
  1002. if (!firstLevelItem || !separator) continue;
  1003. // 拿到可视区域
  1004. QModelIndex firstLevelIndex = model->indexFromItem(firstLevelItem);
  1005. QRect firstLevelRect = treeViewDown->visualRect(firstLevelIndex);
  1006. // 如果这个一级目录滚动到看不见了,就把分割线也藏起来
  1007. if (!firstLevelRect.isValid()) {
  1008. separator->hide();
  1009. continue;
  1010. }
  1011. // 如果展开并且它有子节点,就找“最后一个可见子项”
  1012. if (treeViewDown->isExpanded(firstLevelIndex) && firstLevelItem->hasChildren()) {
  1013. QModelIndex lastVisibleChild = findLastVisibleChild(firstLevelIndex);
  1014. if (lastVisibleChild.isValid()) {
  1015. QRect lastChildRect = treeViewDown->visualRect(lastVisibleChild);
  1016. if (lastChildRect.isValid()) {
  1017. // 将分割线放在最后一个子项下面
  1018. separator->setGeometry(16,lastChildRect.bottom() + 115,widget2->width() - 40,1);
  1019. separator->show();
  1020. continue;
  1021. }
  1022. }
  1023. }
  1024. // 如果收起或找不到可见子项,就放在本一级目录下面
  1025. separator->setGeometry(16,firstLevelRect.bottom() + 115,widget2->width() - 40,1);
  1026. separator->show();
  1027. }
  1028. }
  1029. QModelIndex DbTreeViewManager::findLastVisibleChild(const QModelIndex &parentIndex) {
  1030. if (!parentIndex.isValid()) return QModelIndex();
  1031. int childCount = model->rowCount(parentIndex);
  1032. QModelIndex lastVisible;
  1033. for (int i = childCount - 1; i >= 0; --i) {
  1034. QModelIndex childIndex = model->index(i, 0, parentIndex);
  1035. if (!treeViewDown->isRowHidden(i, parentIndex)) {
  1036. if (treeViewDown->isExpanded(childIndex) && model->rowCount(childIndex) > 0) {
  1037. QModelIndex deeper = findLastVisibleChild(childIndex);
  1038. if (deeper.isValid()) {
  1039. return deeper;
  1040. }
  1041. }
  1042. lastVisible = childIndex;
  1043. break;
  1044. }
  1045. }
  1046. return lastVisible;
  1047. }
  1048. void DbTreeViewManager::displayThirdLevelFields(const QJsonObject &data, bool isHome)
  1049. {
  1050. if (data.isEmpty()) {
  1051. qWarning() << "字段数据为空,无法显示";
  1052. return;
  1053. }
  1054. if (!data.contains("IsThirdLevel") || !data["IsThirdLevel"].toBool()) {
  1055. qWarning() << "不是三级目录,跳过按钮加载";
  1056. return;
  1057. }
  1058. bool allChangeFlag = false;
  1059. if (data.contains("allChangeFlag") && data["allChangeFlag"].isBool()) {
  1060. allChangeFlag = data["allChangeFlag"].toBool();
  1061. }
  1062. else {
  1063. qWarning() << "数据中缺少 'allChangeFlag' 字段或类型不正确";
  1064. }
  1065. // 若已有第三层窗口,先关闭并释放
  1066. if (m_thirdLevelFieldWnd) {
  1067. m_thirdLevelFieldWnd->close();
  1068. m_thirdLevelFieldWnd->deleteLater();
  1069. m_thirdLevelFieldWnd = nullptr;
  1070. }
  1071. // 获取当前选中的目录项,设置状态
  1072. QModelIndex currentIndex = treeViewDown->currentIndex();
  1073. if (currentIndex.isValid()) {
  1074. QStandardItem* currentItem = model->itemFromIndex(currentIndex);
  1075. if (currentItem) {
  1076. currentItem->setCheckState(allChangeFlag ? Qt::Checked : Qt::Unchecked);
  1077. qDebug() << "设置当前目录项复选框状态为:" << (allChangeFlag ? "Checked" : "Unchecked");
  1078. }
  1079. }
  1080. else {
  1081. qWarning() << "当前没有选中的目录项";
  1082. }
  1083. // 隐藏目录树及所有分隔线
  1084. treeViewDown->hide();
  1085. for (auto separator : firstLevelSeparators) {
  1086. if (separator)
  1087. separator->hide();
  1088. }
  1089. // 显示按钮
  1090. loadButtonConfigForThirdLevel(data);
  1091. // 清理之前的控件列表
  1092. m_fieldWidgets.clear();
  1093. // 创建新的 "字段展示" 窗口,并赋值给 m_thirdLevelFieldWnd
  1094. m_thirdLevelFieldWnd = new QWidget(widget2);
  1095. m_thirdLevelFieldWnd->setWindowTitle("字段展示");
  1096. m_thirdLevelFieldWnd->setStyleSheet("background-color: transparent;");
  1097. if (isHome) {
  1098. // Home 界面,填满 widget2
  1099. m_thirdLevelFieldWnd->setGeometry(0, 0, widget2->width(), widget2->height());
  1100. }
  1101. else {
  1102. // 其他配置界面,设置与 treeViewDown 相同的几何位置
  1103. m_thirdLevelFieldWnd->setGeometry(treeViewDown->geometry());
  1104. }
  1105. // 创建滚动区域
  1106. QScrollArea *scrollArea = new QScrollArea(m_thirdLevelFieldWnd);
  1107. scrollArea->setWidgetResizable(true);
  1108. scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
  1109. // 创建滚动容器并设置布局
  1110. QWidget *scrollWidget = new QWidget;
  1111. scrollWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
  1112. QVBoxLayout *scrollLayout = new QVBoxLayout(scrollWidget);
  1113. scrollLayout->setSpacing(10);
  1114. scrollLayout->setContentsMargins(10, 10, 10, 10);
  1115. int previousGroupId = -1;
  1116. // 遍历字段数组
  1117. if (data.contains("fields") && data["fields"].isArray()) {
  1118. QJsonArray fields = data["fields"].toArray();
  1119. for (const QJsonValue &val : fields) {
  1120. QJsonObject field = val.toObject();
  1121. int fieldId = field["Id"].toInt();
  1122. QString fieldName = field["Describe"].toString();
  1123. QString fieldType = field["Type"].toString();
  1124. QString fieldValue = field["Value"].toString();
  1125. QString fieldCurrentValue = field["CurrentValue"].toString();
  1126. QString fieldTableName = field["TableName"].toString();
  1127. QString fieldUpLimit = field["UpLimit"].toString();
  1128. QString fieldDownLimit = field["DownLimit"].toString();
  1129. QString fieldUnits = field["units"].toString();
  1130. int groupId = field["Groupld"].toInt();
  1131. // 如果组变化,插入分隔线
  1132. if (previousGroupId != -1 && groupId != previousGroupId) {
  1133. QFrame *separator = createUnifiedSeparator(scrollWidget, 2);
  1134. QHBoxLayout *separatorLayout = new QHBoxLayout;
  1135. separatorLayout->setContentsMargins(0, 5, 0, 5);
  1136. separatorLayout->addWidget(separator);
  1137. scrollLayout->addLayout(separatorLayout);
  1138. separator->show();
  1139. }
  1140. previousGroupId = groupId;
  1141. // 每个字段一行
  1142. QHBoxLayout *fieldLayout = new QHBoxLayout;
  1143. fieldLayout->setSpacing(5);
  1144. QLabel *label = new QLabel(fieldName);
  1145. label->setAlignment(Qt::AlignVCenter | Qt::AlignLeft);
  1146. label->setFixedHeight(24);
  1147. label->setMinimumWidth(120);
  1148. fieldLayout->addWidget(label);
  1149. fieldLayout->addStretch(1);
  1150. QWidget *rightWidget = new QWidget;
  1151. QHBoxLayout *rightLayout = new QHBoxLayout(rightWidget);
  1152. rightLayout->setContentsMargins(0, 0, 20, 0);
  1153. rightLayout->setSpacing(5);
  1154. QWidget *createdWidget = nullptr;
  1155. if (fieldType == "input") {
  1156. // 检查 Value 中是否包含逗号分隔(比如 "请输入内容1,分钟")
  1157. if (fieldUnits!= "") {
  1158. // // 采用逗号分割,trim去除空白
  1159. // QStringList parts = fieldValue.split(",", Qt::SkipEmptyParts);
  1160. // QString leftText = parts.at(0).trimmed();
  1161. // QString rightText = (parts.size() > 1 ? parts.at(1).trimmed() : QString());
  1162. // 创建 QLineEdit 显示左边文本
  1163. QLineEdit *lineEdit = new QLineEdit();
  1164. if((fieldUpLimit=="")&&(fieldDownLimit=="")){
  1165. lineEdit->setText(fieldCurrentValue);
  1166. lineEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
  1167. lineEdit->setFixedSize(105, 28);
  1168. lineEdit->setAlignment(Qt::AlignLeft);
  1169. lineEdit->setStyleSheet(R"(
  1170. QLineEdit {
  1171. background: #FFFFFF;
  1172. border: 1px solid #BABBDC;
  1173. border-radius: 6px;
  1174. padding: 2px 5px;
  1175. }
  1176. )");
  1177. }else{//上下限至少设置了一个值
  1178. if(fieldCurrentValue == ""){
  1179. lineEdit->setPlaceholderText("请输入数字");
  1180. }else{
  1181. lineEdit->setText(fieldCurrentValue);
  1182. }
  1183. lineEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
  1184. lineEdit->setFixedSize(105, 28);
  1185. lineEdit->setAlignment(Qt::AlignLeft);
  1186. lineEdit->setStyleSheet(R"(
  1187. QLineEdit {
  1188. background: #FFFFFF;
  1189. border: 1px solid #BABBDC;
  1190. border-radius: 6px;
  1191. padding: 2px 5px;
  1192. }
  1193. )");
  1194. }
  1195. // 创建 QLabel 显示右边文本(比如 "分钟")
  1196. QLabel *unitLabel = new QLabel(fieldUnits);
  1197. unitLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
  1198. unitLabel->setFixedHeight(28);
  1199. unitLabel->setStyleSheet("QLabel { font-size: 14px; }");
  1200. // 把 QLineEdit 和 QLabel 水平排列,确保 Qlabel 显示在 QLineEdit 右侧
  1201. QHBoxLayout *inputLayout = new QHBoxLayout;
  1202. inputLayout->setSpacing(10);
  1203. inputLayout->setContentsMargins(0,0,0,0);
  1204. inputLayout->addWidget(lineEdit);
  1205. inputLayout->addWidget(unitLabel);
  1206. // 用一个容器部件来装下这个布局
  1207. QWidget *inputWidget = new QWidget;
  1208. inputWidget->setLayout(inputLayout);
  1209. rightLayout->addWidget(inputWidget);
  1210. // 保存控件指针到 m_fieldWidgets(可选)
  1211. m_fieldWidgets.append(lineEdit);
  1212. m_fieldWidgets.append(unitLabel);
  1213. createdWidget = inputWidget;
  1214. // // 连接 textChanged 信号到 lambda 函数
  1215. connect(lineEdit, &QLineEdit::textChanged, [this,lineEdit,fieldTableName,fieldId,fieldUpLimit,fieldDownLimit]() {
  1216. // qDebug() << "Text changed:" << lineEdit->text();
  1217. // qDebug() << "Text changed:" << fieldName;
  1218. // qDebug() << "Text changed:" << fieldTableName;
  1219. // qDebug() << "Text changed111:" << fieldId;
  1220. if((fieldUpLimit!="")&&(fieldDownLimit!="")){
  1221. int uplimit = fieldUpLimit.toInt();
  1222. int downlimit = fieldDownLimit.toInt();
  1223. int inputvalue = (lineEdit->text()).toInt();
  1224. if((inputvalue<=uplimit)&&(inputvalue>=downlimit)){
  1225. updateDb(fieldTableName,fieldId,lineEdit->text());
  1226. }else{
  1227. lineEdit->setPlaceholderText("超出设定范围,请重新输入");
  1228. }
  1229. }else if(fieldDownLimit!=""){
  1230. int downlimit = fieldDownLimit.toInt();
  1231. int inputvalue = (lineEdit->text()).toInt();
  1232. if(inputvalue>=downlimit){
  1233. updateDb(fieldTableName,fieldId,lineEdit->text());
  1234. }else{
  1235. lineEdit->setPlaceholderText("超出设定范围,请重新输入");
  1236. }
  1237. }else if(fieldUpLimit!=""){
  1238. int uplimit = fieldUpLimit.toInt();
  1239. int inputvalue = (lineEdit->text()).toInt();
  1240. if(inputvalue<=uplimit){
  1241. updateDb(fieldTableName,fieldId,lineEdit->text());
  1242. }else{
  1243. lineEdit->setPlaceholderText("超出设定范围,请重新输入");
  1244. }
  1245. }else{
  1246. updateDb(fieldTableName,fieldId,lineEdit->text());
  1247. }
  1248. });
  1249. } else {
  1250. // 如果不包含逗号,按原有逻辑只创建 QLineEdit
  1251. QLineEdit *lineEdit1 = new QLineEdit(fieldCurrentValue);
  1252. lineEdit1->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
  1253. lineEdit1->setFixedSize(140, 28);
  1254. lineEdit1->setAlignment(Qt::AlignLeft);
  1255. lineEdit1->setStyleSheet(R"(
  1256. QLineEdit {
  1257. background: #FFFFFF;
  1258. border: 1px solid #BABBDC;
  1259. border-radius: 6px;
  1260. padding: 2px 5px;
  1261. }
  1262. )");
  1263. rightLayout->addWidget(lineEdit1);
  1264. createdWidget = lineEdit1;
  1265. // // 连接 textChanged 信号到 lambda 函数
  1266. connect(lineEdit1, &QLineEdit::textChanged, [this,lineEdit1,fieldTableName,fieldId]() {
  1267. // qDebug() << "Text changed:" << lineEdit1->text();
  1268. // qDebug() << "Text changed:" << fieldName;
  1269. updateDb(fieldTableName,fieldId,lineEdit1->text());
  1270. // 在这里添加你想要执行的操作
  1271. });
  1272. }
  1273. }
  1274. else if (fieldType == "radio") {
  1275. // 用逗号分隔的选项
  1276. QStringList optionList = fieldValue.split(QRegExp("[,,]"), Qt::SkipEmptyParts);
  1277. QHBoxLayout *radioLayout = new QHBoxLayout;
  1278. radioLayout->setSpacing(5);
  1279. QButtonGroup *radioGroup = new QButtonGroup(rightWidget);
  1280. for (const QString &optionText : optionList) {
  1281. QString trimmedOpt = optionText.trimmed();
  1282. if (trimmedOpt.isEmpty()) continue;
  1283. QRadioButton *radioButton = new QRadioButton(trimmedOpt);
  1284. radioGroup->addButton(radioButton);
  1285. radioLayout->addWidget(radioButton);
  1286. m_fieldWidgets.append(radioButton);
  1287. if(fieldCurrentValue == trimmedOpt){
  1288. radioButton->setChecked(true);
  1289. }
  1290. }
  1291. // 使用Lambda函数连接 buttonToggled 信号
  1292. connect(radioGroup, static_cast<void (QButtonGroup::*)(QAbstractButton *, bool)>(&QButtonGroup::buttonToggled),[this,fieldTableName,fieldId](QAbstractButton *button,bool checked) {
  1293. if (checked) {
  1294. // qDebug() << "Button toggled:" << button->text();
  1295. // 在这里添加你想要执行的操作
  1296. updateDb(fieldTableName,fieldId,button->text());
  1297. }
  1298. });
  1299. rightLayout->addLayout(radioLayout);
  1300. }
  1301. else if (fieldType == "checkbox") {
  1302. bool isChecked;
  1303. if(fieldCurrentValue == ""){
  1304. isChecked = (fieldValue == "1");
  1305. }else{
  1306. isChecked = (fieldCurrentValue == "1");
  1307. }
  1308. QCheckBox *checkBox = new QCheckBox;
  1309. checkBox->setChecked(isChecked);
  1310. checkBox->setStyleSheet(R"(
  1311. QCheckBox::indicator {
  1312. width: 20px;
  1313. height: 20px;
  1314. }
  1315. QCheckBox::indicator:unchecked {
  1316. background-color: #FFFFFF;
  1317. border: 1px solid #BABBDC;
  1318. border-radius: 2px;
  1319. }
  1320. QCheckBox::indicator:checked {
  1321. image: url(:/images/three_Selecte.png);
  1322. }
  1323. QCheckBox {
  1324. spacing: 0px;
  1325. }
  1326. )");
  1327. rightLayout->addWidget(checkBox);
  1328. createdWidget = checkBox;
  1329. connect(checkBox, &QCheckBox::stateChanged, [this,fieldTableName,fieldId](int state) {
  1330. if (state == Qt::Checked) {
  1331. // qDebug() << "CheckBox is checked"<<fieldId;
  1332. updateDb(fieldTableName,fieldId,"1");
  1333. } else if (state == Qt::Unchecked) {
  1334. // qDebug() << "CheckBox is unchecked"<<fieldId;
  1335. // 在这里添加你想要执行的操作
  1336. updateDb(fieldTableName,fieldId,"0");
  1337. } else if (state == Qt::PartiallyChecked) {
  1338. qDebug() << "CheckBox is partially checked";
  1339. // 在这里添加你想要执行的操作
  1340. }
  1341. });
  1342. }
  1343. else if (fieldType == "dropdown") {
  1344. QStringList optionList = fieldValue.split(QRegExp("[,,]"), Qt::SkipEmptyParts);
  1345. QComboBox *comboBox = new QComboBox;
  1346. comboBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
  1347. comboBox->setFixedSize(140, 28);
  1348. comboBox->setStyleSheet(R"(
  1349. QComboBox {
  1350. background: #FFFFFF;
  1351. border: 1px solid #BABBDC;
  1352. border-radius: 6px;
  1353. padding: 2px 5px;
  1354. }
  1355. QComboBox::drop-down {
  1356. width: 20px;
  1357. }
  1358. )");
  1359. // int newIndex = -1;
  1360. for (const QString &opt : optionList) {
  1361. QString trimmedOpt = opt.trimmed();
  1362. if (!trimmedOpt.isEmpty())
  1363. comboBox->addItem(trimmedOpt);
  1364. }
  1365. if(fieldCurrentValue == ""){
  1366. comboBox->setCurrentIndex(0);
  1367. }else{
  1368. comboBox->setCurrentIndex(fieldCurrentValue.toInt());
  1369. }
  1370. rightLayout->addWidget(comboBox);
  1371. createdWidget = comboBox;
  1372. // 使用Lambda函数连接 currentIndexChanged 信号
  1373. connect(comboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), [this,comboBox,fieldTableName,fieldId](int index) {
  1374. QString selectedText = comboBox->itemText(index);
  1375. QString indexString = QString::number(index);
  1376. // qDebug() << "ComboBox index changed to:" << index << "Text:" << selectedText;
  1377. updateDb(fieldTableName,fieldId,indexString);
  1378. // 在这里添加你想要执行的操作
  1379. });
  1380. }
  1381. else if (fieldType == "time") {
  1382. QTimeEdit *timeEdit = new QTimeEdit;
  1383. timeEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
  1384. timeEdit->setFixedSize(120, 28);
  1385. timeEdit->setStyleSheet(R"(
  1386. QTimeEdit {
  1387. background: #FFFFFF;
  1388. border: 1px solid #BABBDC;
  1389. border-radius: 6px;
  1390. padding: 2px 5px;
  1391. }
  1392. )");
  1393. timeEdit->setDisplayFormat("HH:mm:ss");
  1394. timeEdit->setTime(QTime::fromString(fieldValue, "HH:mm:ss"));
  1395. rightLayout->addWidget(timeEdit);
  1396. createdWidget = timeEdit;
  1397. }
  1398. else if (fieldType == "switch") {
  1399. QWidget *switchContainer = new QWidget;
  1400. QHBoxLayout *switchLayout = new QHBoxLayout(switchContainer);
  1401. switchLayout->setSpacing(5);
  1402. switchLayout->setContentsMargins(0, 0, 0, 0);
  1403. QCheckBox *switchBox = new QCheckBox;
  1404. switchBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
  1405. switchBox->setFixedSize(30, 30);
  1406. switchBox->setStyleSheet(R"(
  1407. QCheckBox::indicator {
  1408. width: 30px;
  1409. height: 30px;
  1410. }
  1411. QCheckBox::indicator:unchecked {
  1412. background-color: #BABBDC;
  1413. border-radius: 6px;
  1414. }
  1415. QCheckBox::indicator:checked {
  1416. background-color: #4CAF50;
  1417. border-radius: 6px;
  1418. }
  1419. )");
  1420. QString switchValue;
  1421. if(fieldCurrentValue==""){
  1422. switchValue = fieldValue.toLower();
  1423. }else{
  1424. switchValue = fieldCurrentValue.toLower();
  1425. }
  1426. if (switchValue == "on")
  1427. switchBox->setChecked(true);
  1428. else
  1429. switchBox->setChecked(false);
  1430. QLabel *switchLabel = new QLabel(switchBox->isChecked() ? "开" : "关");
  1431. switchLabel->setAlignment(Qt::AlignVCenter | Qt::AlignLeft);
  1432. switchLabel->setStyleSheet("font-size: 14px;");
  1433. connect(switchBox, &QCheckBox::stateChanged, [fieldTableName,fieldId,switchLabel, this](int state){
  1434. if (state == Qt::Checked){
  1435. switchLabel->setText("开");
  1436. updateDb(fieldTableName,fieldId,"on");
  1437. }else{
  1438. switchLabel->setText("关");
  1439. updateDb(fieldTableName,fieldId,"off");
  1440. }
  1441. });
  1442. switchLayout->addWidget(switchBox);
  1443. switchLayout->addWidget(switchLabel);
  1444. rightLayout->addWidget(switchContainer);
  1445. createdWidget = switchBox;
  1446. }
  1447. else if (fieldType == "combined") {
  1448. // 用逗号分隔
  1449. QStringList parts = fieldValue.split(QRegExp("[,,]"), Qt::SkipEmptyParts);
  1450. QString inputText = (parts.size() >= 1 ? parts.at(0).trimmed() : QString());
  1451. QString button1Text = (parts.size() >= 2 ? parts.at(1).trimmed() : QStringLiteral("获取"));
  1452. QString button2Text = (parts.size() >= 3 ? parts.at(2).trimmed() : QStringLiteral("设置"));
  1453. QLineEdit *comboInput = new QLineEdit(inputText);
  1454. comboInput->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
  1455. comboInput->setFixedHeight(28);
  1456. comboInput->setStyleSheet(R"(
  1457. QLineEdit {
  1458. background: #FFFFFF;
  1459. border: 1px solid #BABBDC;
  1460. border-radius: 5px;
  1461. padding: 2px 5px;
  1462. }
  1463. )");
  1464. m_fieldWidgets.append(comboInput);
  1465. QWidget *combinedWidget = new QWidget;
  1466. QHBoxLayout *combinedLayout = new QHBoxLayout(combinedWidget);
  1467. combinedLayout->setSpacing(5);
  1468. combinedLayout->setContentsMargins(0, 0, 0, 0);
  1469. QPushButton *btnGet = new QPushButton(button1Text, combinedWidget);
  1470. btnGet->setFixedSize(80, 28);
  1471. btnGet->setStyleSheet(R"(
  1472. QPushButton {
  1473. background: #FFFFFF;
  1474. border: 1px solid #BABBDC;
  1475. border-radius: 5px;
  1476. }
  1477. QPushButton:hover {
  1478. background-color: #F0F0F0;
  1479. }
  1480. )");
  1481. m_fieldWidgets.append(btnGet);
  1482. QPushButton *btnSet = new QPushButton(button2Text, combinedWidget);
  1483. btnSet->setFixedSize(80, 28);
  1484. btnSet->setStyleSheet(R"(
  1485. QPushButton {
  1486. background: #FFFFFF;
  1487. border: 1px solid #BABBDC;
  1488. border-radius: 5px;
  1489. }
  1490. QPushButton:hover {
  1491. background-color: #F0F0F0;
  1492. }
  1493. )");
  1494. m_fieldWidgets.append(btnSet);
  1495. combinedLayout->addWidget(comboInput);
  1496. combinedLayout->addWidget(btnGet);
  1497. combinedLayout->addWidget(btnSet);
  1498. combinedLayout->addStretch();
  1499. rightLayout->addWidget(combinedWidget);
  1500. }
  1501. else {
  1502. qWarning() << "未知字段类型:" << fieldType;
  1503. }
  1504. if (createdWidget)
  1505. m_fieldWidgets.append(createdWidget);
  1506. fieldLayout->addWidget(rightWidget);
  1507. scrollLayout->addLayout(fieldLayout);
  1508. }
  1509. }
  1510. scrollLayout->addStretch();
  1511. scrollArea->setWidget(scrollWidget);
  1512. QVBoxLayout *mainLayout = new QVBoxLayout(m_thirdLevelFieldWnd);
  1513. mainLayout->setContentsMargins(0, 0, 0, 0);
  1514. mainLayout->addWidget(scrollArea);
  1515. m_thirdLevelFieldWnd->show();
  1516. }
  1517. void DbTreeViewManager::updateParentCheckState(QStandardItem *item)
  1518. {
  1519. if (!item)
  1520. return;
  1521. QStandardItem *parentItem = item->parent();
  1522. if (!parentItem)
  1523. return;
  1524. bool allChecked = true;
  1525. bool noneChecked = true;
  1526. for (int i = 0; i < parentItem->rowCount(); ++i) {
  1527. QStandardItem *child = parentItem->child(i);
  1528. if (child->checkState() != Qt::Checked) {
  1529. allChecked = false;
  1530. }
  1531. if (child->checkState() == Qt::Checked) {
  1532. noneChecked = false;
  1533. }
  1534. }
  1535. if (allChecked) {
  1536. parentItem->setCheckState(Qt::Checked);
  1537. } else {
  1538. parentItem->setCheckState(Qt::Unchecked);
  1539. }
  1540. if (noneChecked) {
  1541. qDebug() << "noneChecked状态为:" << noneChecked;
  1542. }
  1543. // 递归更新上一级
  1544. updateParentCheckState(parentItem);
  1545. }
  1546. void DbTreeViewManager::onButtonBackClicked()
  1547. {
  1548. if (m_thirdLevelFieldWnd) {
  1549. // 当前在第三层目录,返回到上一层目录
  1550. qDebug() << "当前在第三层目录,准备返回上一层。";
  1551. for(int i=0;i<5;i++){
  1552. if(currentMenuId == menuArray[i].menuId){
  1553. menuArray[i].isthird = false;
  1554. }
  1555. }
  1556. // 关闭并销毁字段展示窗口
  1557. m_thirdLevelFieldWnd->close();
  1558. m_thirdLevelFieldWnd->deleteLater();
  1559. m_thirdLevelFieldWnd = nullptr;
  1560. // 显示目录树和分隔线
  1561. treeViewDown->show();
  1562. for (auto separator : firstLevelSeparators) {
  1563. if (separator)
  1564. separator->show();
  1565. }
  1566. // 获取当前导航路径
  1567. QStringList path;
  1568. QLayout* layout = navigationWidget->layout();
  1569. if (!layout) {
  1570. qWarning() << "导航栏没有布局,无法获取路径。";
  1571. return;
  1572. }
  1573. for (int i = 0; i < layout->count(); ++i) {
  1574. QLayoutItem* item = layout->itemAt(i);
  1575. if (item && item->widget()) {
  1576. QLabel* label = qobject_cast<QLabel*>(item->widget());
  1577. if (label) {
  1578. QString text = label->text().trimmed();
  1579. if (!text.isEmpty()) {
  1580. path << text;
  1581. }
  1582. }
  1583. }
  1584. }
  1585. if (path.isEmpty()) {
  1586. qWarning() << "导航路径为空,无法返回上一层。";
  1587. return;
  1588. }
  1589. // 移除最后一个目录名称以返回上一层
  1590. path.removeLast();
  1591. if (path.isEmpty()) {
  1592. qDebug() << "已经在根目录,无法返回。";
  1593. return;
  1594. }
  1595. // 根据新的路径查找对应的 QModelIndex
  1596. QModelIndex parentIndex = findItemByPath(path);
  1597. if (!parentIndex.isValid()) {
  1598. qWarning() << "无法找到路径对应的目录项:" << path;
  1599. return;
  1600. }
  1601. // 选中父目录项
  1602. treeViewDown->setCurrentIndex(parentIndex);
  1603. treeViewDown->scrollTo(parentIndex);
  1604. // 更新导航栏
  1605. updateNavigationBar(parentIndex);
  1606. // 检查父目录是否为第三层目录
  1607. QStandardItem* parentItem = model->itemFromIndex(parentIndex);
  1608. if (!parentItem) {
  1609. qWarning() << "父目录项无效。";
  1610. return;
  1611. }
  1612. QVariant dataVar = parentItem->data(Qt::UserRole + 2);
  1613. bool isThirdLevel = false;
  1614. int directoryId = -1;
  1615. if (dataVar.canConvert<QJsonObject>()) {
  1616. QJsonObject dataObj = dataVar.toJsonObject();
  1617. if (dataObj.contains("IsThirdLevel") && dataObj["IsThirdLevel"].toBool()) {
  1618. isThirdLevel = true;
  1619. if (dataObj.contains("Id")) {
  1620. directoryId = dataObj["Id"].toInt();
  1621. }
  1622. }
  1623. }
  1624. if (isThirdLevel) {
  1625. if (directoryId == -1) {
  1626. qWarning() << "无效的 DirectoryId,无法加载第三层目录内容。";
  1627. return;
  1628. }
  1629. int userPrivilege = 0x1; // 当前用户的权限等级
  1630. // 获取第三层目录的数据
  1631. QJsonObject data = fetchThirdLevelData(directoryId, userPrivilege);
  1632. // 显示字段展示窗口
  1633. displayThirdLevelFields(data, false); // 传递参数表示非 Home 界面
  1634. } else {
  1635. // 父目录不是第三层目录,确保目录树和分隔线可见
  1636. treeViewDown->show();
  1637. for (auto separator : firstLevelSeparators) {
  1638. if (separator)
  1639. separator->show();
  1640. }
  1641. }
  1642. return;
  1643. }
  1644. // 如果不在第三层目录,则在目录树中返回上一层
  1645. qDebug() << "当前不在第三层目录,尝试在目录树中返回上一层。";
  1646. QModelIndex currentIndex = treeViewDown->currentIndex();
  1647. if (!currentIndex.isValid()) {
  1648. qWarning() << "当前没有选中的目录项,无法返回。";
  1649. return;
  1650. }
  1651. QStandardItem* currentItem = model->itemFromIndex(currentIndex);
  1652. if (!currentItem) {
  1653. qWarning() << "当前选中的目录项无效。";
  1654. return;
  1655. }
  1656. QStandardItem* parentItem = currentItem->parent();
  1657. if (!parentItem) {
  1658. qDebug() << "当前已经在根目录,无法返回。";
  1659. return;
  1660. }
  1661. QModelIndex parentIndex = model->indexFromItem(parentItem);
  1662. if (!parentIndex.isValid()) {
  1663. qWarning() << "父目录的 QModelIndex 无效。";
  1664. return;
  1665. }
  1666. // 选中父目录项
  1667. treeViewDown->setCurrentIndex(parentIndex);
  1668. treeViewDown->scrollTo(parentIndex);
  1669. // 更新导航栏
  1670. updateNavigationBar(parentIndex);
  1671. // 检查父目录是否为第三层目录
  1672. QVariant dataVar = parentItem->data(Qt::UserRole + 2);
  1673. bool isThirdLevel = false;
  1674. int directoryId = -1;
  1675. if (dataVar.canConvert<QJsonObject>()) {
  1676. QJsonObject dataObj = dataVar.toJsonObject();
  1677. if (dataObj.contains("IsThirdLevel") && dataObj["IsThirdLevel"].toBool()) {
  1678. isThirdLevel = true;
  1679. if (dataObj.contains("Id")) {
  1680. directoryId = dataObj["Id"].toInt();
  1681. }
  1682. }
  1683. }
  1684. if (isThirdLevel) {
  1685. if (directoryId == -1) {
  1686. qWarning() << "无效的 DirectoryId,无法加载第三层目录内容。";
  1687. return;
  1688. }
  1689. int userPrivilege = 0x1; // 根据实际情况获取当前用户的权限等级
  1690. QJsonObject data = fetchThirdLevelData(directoryId, userPrivilege);
  1691. displayThirdLevelFields(data, false); // 传递参数表示非 Home 界面
  1692. }
  1693. }
  1694. QList<QStandardItem*> DbTreeViewManager::collectAllThirdLevelItems()
  1695. {
  1696. QList<QStandardItem*> result;
  1697. // 从根节点开始递归搜集
  1698. QStandardItem *root = model->invisibleRootItem();
  1699. if (!root) return result;
  1700. std::function<void(QStandardItem*)> dfsCollectThirdLevel;
  1701. dfsCollectThirdLevel = [&](QStandardItem* parentItem)
  1702. {
  1703. if (!parentItem) return;
  1704. int rowCount = parentItem->rowCount();
  1705. for (int i = 0; i < rowCount; ++i) {
  1706. QStandardItem *child = parentItem->child(i);
  1707. if (!child) continue;
  1708. // 判断是否是第三层
  1709. QVariant dataVar = child->data(Qt::UserRole + 2);
  1710. if (dataVar.canConvert<QJsonObject>()) {
  1711. QJsonObject obj = dataVar.toJsonObject();
  1712. if (obj.contains("IsThirdLevel") && obj["IsThirdLevel"].toBool()) {
  1713. // 收集这个第三层节点
  1714. result.append(child);
  1715. }
  1716. }
  1717. // 即使不是第三层,也要继续往下找子节点
  1718. dfsCollectThirdLevel(child);
  1719. }
  1720. };
  1721. dfsCollectThirdLevel(root);
  1722. return result;
  1723. }
  1724. void DbTreeViewManager::onButtonDownClicked()
  1725. {
  1726. // 1) 收集所有 第三层 节点
  1727. QList<QStandardItem*> thirdLevelList = collectAllThirdLevelItems();
  1728. if (thirdLevelList.isEmpty()) {
  1729. qDebug() << "[onButtonDownClicked] 没有任何三级目录,无法遍历。";
  1730. return;
  1731. }
  1732. // 2) 找到 当前选中的节点 在 thirdLevelList 里的索引
  1733. QModelIndex curIndex = treeViewDown->currentIndex();
  1734. if (!curIndex.isValid()) {
  1735. qDebug() << "[onButtonDownClicked] 当前没有选中节点,默认跳到第一个三级目录。";
  1736. // 如果想默认跳到第一个
  1737. QStandardItem *firstItem = thirdLevelList.first();
  1738. QModelIndex idx = model->indexFromItem(firstItem);
  1739. treeViewDown->setCurrentIndex(idx);
  1740. // 模拟点击一下
  1741. onTreeViewClicked_updown(idx);
  1742. // 保存复选框状态
  1743. saveCheckedPaths();
  1744. // 保存展开路径
  1745. saveExpandedPaths();
  1746. return;
  1747. }
  1748. QStandardItem *curItem = model->itemFromIndex(curIndex);
  1749. if (!curItem) {
  1750. qWarning() << "[onButtonDownClicked] currentItem 无效。";
  1751. return;
  1752. }
  1753. // 若不是三级目录,就先找它最近的父级是不是三级目录,否则当做没找到。
  1754. int currentPos = -1;
  1755. {
  1756. // 在 thirdLevelList 里找到 curItem
  1757. currentPos = thirdLevelList.indexOf(curItem);
  1758. if (currentPos < 0) {
  1759. qDebug() << "[onButtonDownClicked] 当前节点不是三级目录,尝试找父级是不是三级目录…";
  1760. // 向上找父节点是否在 thirdLevelList 里
  1761. QStandardItem *temp = curItem->parent();
  1762. while (temp) {
  1763. int pos = thirdLevelList.indexOf(temp);
  1764. if (pos >= 0) {
  1765. currentPos = pos;
  1766. break;
  1767. }
  1768. temp = temp->parent();
  1769. }
  1770. if (currentPos < 0) {
  1771. qDebug() << "还是找不到,说明当前目录不属于任何三级目录,直接跳到第一个";
  1772. QStandardItem *firstItem = thirdLevelList.first();
  1773. QModelIndex idx = model->indexFromItem(firstItem);
  1774. treeViewDown->setCurrentIndex(idx);
  1775. onTreeViewClicked_updown(idx);
  1776. // 保存复选框状态
  1777. saveCheckedPaths();
  1778. // 保存展开路径
  1779. saveExpandedPaths();
  1780. return;
  1781. }
  1782. }
  1783. }
  1784. // 尝试下一个
  1785. int nextPos = currentPos + 1;
  1786. if (nextPos >= thirdLevelList.size()) {
  1787. qDebug() << "[onButtonDownClicked] 已经是最后一个三级目录了,无法再向下。";
  1788. return;
  1789. }
  1790. // 跳到下一个
  1791. QStandardItem *nextItem = thirdLevelList[nextPos];
  1792. QModelIndex nextIndex = model->indexFromItem(nextItem);
  1793. treeViewDown->setCurrentIndex(nextIndex);
  1794. // 相当于模拟点击
  1795. onTreeViewClicked_updown(nextIndex);
  1796. // 保存复选框状态
  1797. saveCheckedPaths();
  1798. // 保存展开路径
  1799. saveExpandedPaths();
  1800. }
  1801. void DbTreeViewManager::onButtonUpClicked()
  1802. {
  1803. // 1) 收集所有 第三层 节点
  1804. QList<QStandardItem*> thirdLevelList = collectAllThirdLevelItems();
  1805. if (thirdLevelList.isEmpty()) {
  1806. qDebug() << "[onButtonUpClicked] 没有任何三级目录,无法遍历。";
  1807. return;
  1808. }
  1809. // 2) 找到 当前选中的节点
  1810. QModelIndex curIndex = treeViewDown->currentIndex();
  1811. if (!curIndex.isValid()) {
  1812. qDebug() << "[onButtonUpClicked] 当前无选中节点,默认跳到最后一个三级目录。";
  1813. // 跳到最后一个
  1814. QStandardItem *lastItem = thirdLevelList.last();
  1815. QModelIndex idx = model->indexFromItem(lastItem);
  1816. treeViewDown->setCurrentIndex(idx);
  1817. // 模拟点击
  1818. onTreeViewClicked_updown(idx);
  1819. // 保存复选框状态
  1820. saveCheckedPaths();
  1821. // 保存展开路径
  1822. saveExpandedPaths();
  1823. return;
  1824. }
  1825. QStandardItem *curItem = model->itemFromIndex(curIndex);
  1826. if (!curItem) {
  1827. qWarning() << "[onButtonUpClicked] currentItem 无效。";
  1828. return;
  1829. }
  1830. // 如果当前节点不是三级目录, 向上查找
  1831. int currentPos = thirdLevelList.indexOf(curItem);
  1832. if (currentPos < 0) {
  1833. qDebug() << "[onButtonUpClicked] 当前节点不是三级目录,尝试找父级是不是三级目录。";
  1834. QStandardItem *temp = curItem->parent();
  1835. while (temp) {
  1836. int pos = thirdLevelList.indexOf(temp);
  1837. if (pos >= 0) {
  1838. currentPos = pos;
  1839. break;
  1840. }
  1841. temp = temp->parent();
  1842. }
  1843. if (currentPos < 0) {
  1844. qDebug() << "找不到任何三级目录,直接跳到最后一个。";
  1845. QStandardItem *lastItem = thirdLevelList.last();
  1846. QModelIndex idx = model->indexFromItem(lastItem);
  1847. treeViewDown->setCurrentIndex(idx);
  1848. onTreeViewClicked_updown(idx);
  1849. // 保存复选框状态
  1850. saveCheckedPaths();
  1851. // 保存展开路径
  1852. saveExpandedPaths();
  1853. return;
  1854. }
  1855. }
  1856. // 尝试上一个
  1857. int prevPos = currentPos - 1;
  1858. if (prevPos < 0) {
  1859. qDebug() << "[onButtonUpClicked] 已经是第一个三级目录了,无法再向上。";
  1860. return;
  1861. }
  1862. // 跳到上一个
  1863. QStandardItem *prevItem = thirdLevelList[prevPos];
  1864. QModelIndex prevIndex = model->indexFromItem(prevItem);
  1865. treeViewDown->setCurrentIndex(prevIndex);
  1866. // 模拟点击
  1867. onTreeViewClicked_updown(prevIndex);
  1868. // 保存复选框状态
  1869. saveCheckedPaths();
  1870. // 保存展开路径
  1871. saveExpandedPaths();
  1872. }
  1873. void DbTreeViewManager::onButtonRightClicked()
  1874. {
  1875. if (m_forwardStack.isEmpty()) {
  1876. qDebug() << "[Forward] 已经没有可以前进的页面";
  1877. buttonRight->setIcon(QIcon(":/images/home_right.png"));
  1878. return;
  1879. }
  1880. // 1. 弹出 forwardStack 的最后一个
  1881. PageState st = m_forwardStack.takeLast();
  1882. // 2. 把当前页面 push 到 backStack
  1883. PageState cur = getCurrentPageState();
  1884. m_backStack.append(cur);
  1885. if(m_backStack.size() >= 2){
  1886. buttonLeft->setIcon(QIcon(":/images/home_left.png"));
  1887. }
  1888. // 3. 加载 st
  1889. loadPageState(st, true);
  1890. }
  1891. void DbTreeViewManager::onButtonLeftClicked()
  1892. {
  1893. if (m_backStack.size() < 2) {
  1894. qDebug() << "[Back] 已经无法再后退";
  1895. buttonLeft->setIcon(QIcon(":/images/home_left_hide.png"));
  1896. return;
  1897. }
  1898. // 1. 先把当前页面(相当于 m_backStack 最后一个)弹出,放到 forwardStack
  1899. PageState cur = m_backStack.takeLast();
  1900. if(m_backStack.size() >= 2){
  1901. buttonLeft->setIcon(QIcon(":/images/home_left.png"));
  1902. }else{
  1903. buttonLeft->setIcon(QIcon(":/images/home_left_hide.png"));
  1904. }
  1905. m_forwardStack.append(cur);
  1906. buttonRight->setIcon(QIcon(":/images/home_right_show.png"));
  1907. // 2. 拿到新的 m_backStack 末尾(即上一次看的页面)
  1908. const PageState &prev = m_backStack.last();
  1909. // 3. 加载 prev
  1910. loadPageState(prev, true );
  1911. }
  1912. // 构建节点的完整路径
  1913. QStringList DbTreeViewManager::buildItemPath(QStandardItem *item)
  1914. {
  1915. QStringList path;
  1916. QStandardItem *currentItem = item;
  1917. while (currentItem) {
  1918. path.prepend(currentItem->text());
  1919. currentItem = currentItem->parent();
  1920. }
  1921. return path;
  1922. }
  1923. // 根据路径查找对应的节点
  1924. QModelIndex DbTreeViewManager::findItemByPath(const QStringList &path)
  1925. {
  1926. if (path.isEmpty()) return QModelIndex();
  1927. QStandardItem *currentItem = model->invisibleRootItem();
  1928. QModelIndex currentIndex;
  1929. for (const QString &part : path) {
  1930. bool found = false;
  1931. for (int i = 0; i < currentItem->rowCount(); ++i) {
  1932. QStandardItem *child = currentItem->child(i);
  1933. if (child->text() == part) {
  1934. currentIndex = model->indexFromItem(child);
  1935. currentItem = child;
  1936. found = true;
  1937. qDebug() << "找到路径部分:" << part;
  1938. break;
  1939. }
  1940. }
  1941. if (!found) {
  1942. qWarning() << "路径部分未找到:" << part;
  1943. return QModelIndex();
  1944. }
  1945. }
  1946. return currentIndex;
  1947. }
  1948. void DbTreeViewManager::setCheckedPaths(const QStringList &checkedPathsList)
  1949. {
  1950. m_blockItemChanged = true;
  1951. for (const QString &pathStr : checkedPathsList) {
  1952. QStringList path = pathStr.split("/");
  1953. QModelIndex idx = findItemByPath(path);
  1954. if (idx.isValid()) {
  1955. QStandardItem *item = model->itemFromIndex(idx);
  1956. if (item) {
  1957. item->setCheckState(Qt::Checked);
  1958. qDebug() << " Setting item:" << item->text() << "to Checked";
  1959. }
  1960. } else {
  1961. qDebug() << "Path not found:" << pathStr;
  1962. }
  1963. }
  1964. m_blockItemChanged = false;
  1965. }
  1966. // 递归收集被选中的路径
  1967. QStringList DbTreeViewManager::collectCheckedPathsRecursive(QStandardItem *item, QStringList path)
  1968. {
  1969. QStringList checkedList;
  1970. if (!item) {
  1971. item = model->invisibleRootItem();
  1972. }
  1973. for (int i = 0; i < item->rowCount(); ++i) {
  1974. QStandardItem *child = item->child(i);
  1975. if (child) {
  1976. QStringList currentPath = path;
  1977. currentPath << child->text();
  1978. if (child->checkState() == Qt::Checked) {
  1979. checkedList << currentPath.join("/");
  1980. }
  1981. // 递归收集子项
  1982. checkedList << collectCheckedPathsRecursive(child, currentPath);
  1983. }
  1984. }
  1985. return checkedList;
  1986. }
  1987. // 收集所有被选中的复选框路径
  1988. QStringList DbTreeViewManager::collectCheckedPaths()
  1989. {
  1990. return collectCheckedPathsRecursive(model->invisibleRootItem(), QStringList());
  1991. }
  1992. // 更新父项的复选框状态
  1993. void DbTreeViewManager::updateParentItems(QStandardItem *parentItem)
  1994. {
  1995. if (!parentItem)
  1996. return;
  1997. int checkedCount = 0;
  1998. int totalCount = parentItem->rowCount();
  1999. qDebug() << "Updating child items of:" << parentItem->text();
  2000. for (int i = 0; i < totalCount; ++i)
  2001. {
  2002. QStandardItem *child = parentItem->child(i);
  2003. if (child && child->checkState() == Qt::Checked)
  2004. {
  2005. checkedCount++;
  2006. }
  2007. }
  2008. if (checkedCount == totalCount)
  2009. {
  2010. parentItem->setCheckState(Qt::Checked);
  2011. }
  2012. else
  2013. {
  2014. parentItem->setCheckState(Qt::Unchecked);
  2015. }
  2016. // 递归更新上层父项
  2017. updateParentItems(parentItem->parent());
  2018. }
  2019. // 加载并显示三级目录对应按钮配置信息
  2020. void DbTreeViewManager::loadButtonConfigForThirdLevel(const QJsonObject &thirdLevelObj)
  2021. {
  2022. if (!m_originalWnd) {
  2023. qWarning() << "OriginalWnd 指针为空,无法加载按钮配置";
  2024. return;
  2025. }
  2026. if (!thirdLevelObj.contains("buttons")) {
  2027. qWarning() << "三级目录配置中不包含 'buttons' 字段";
  2028. return;
  2029. }
  2030. QJsonArray buttonsArray = thirdLevelObj.value("buttons").toArray();
  2031. // 获取 widget_left
  2032. QWidget* widgetLeft = m_originalWnd->getWidgetLeft();
  2033. if (!widgetLeft) {
  2034. qWarning() << "无法访问 widget_left";
  2035. return;
  2036. }
  2037. // 清空 widget_left 中由 loadButtonConfigForThirdLevel 创建的按钮
  2038. QList<QPushButton*> existingButtons = widgetLeft->findChildren<QPushButton*>();
  2039. for (QPushButton* button : existingButtons) {
  2040. if (button->objectName().startsWith("thirdLevelBtn_")) { // 仅删除特定按钮
  2041. button->deleteLater();
  2042. }
  2043. }
  2044. // 使用绝对定位创建按钮
  2045. for (int i = 0; i < buttonsArray.size() && i < 12; ++i) {
  2046. QJsonObject buttonObj = buttonsArray[i].toObject();
  2047. QString buttonId = buttonObj.value("id").toString();
  2048. QString buttonIcon = buttonObj.value("icon").toString();
  2049. QString buttonText = buttonObj.value("text").toString();
  2050. bool isEnabled = buttonObj.value("enabled").toBool();
  2051. // 创建按钮
  2052. QPushButton *button = new QPushButton(widgetLeft);
  2053. button->setObjectName("thirdLevelBtn_" + buttonId); // 设置带前缀的对象名称
  2054. // 设置按钮的样式,调整图标和文本的位置
  2055. button->setStyleSheet(R"(
  2056. QPushButton {
  2057. position: absolute;
  2058. border-radius: 6px;
  2059. opacity: 1;
  2060. background: #CBD0FF;
  2061. border: none;
  2062. }
  2063. QPushButton:hover {
  2064. background-color: #A9B4FF; /* 鼠标悬停效果 */
  2065. }
  2066. )");
  2067. // 设置按钮的位置和大小
  2068. int x = 16;
  2069. int y = 245 + i * (48 + 13); // 第一个按钮 y=245,后续每个按钮间隔13px
  2070. button->setGeometry(x, y, 158, 48);
  2071. // 设置按钮的可见性,根据 "enabled" 字段显示或隐藏按钮
  2072. button->setVisible(isEnabled);
  2073. // 创建图标标签
  2074. QLabel *iconLabel = new QLabel(button);
  2075. iconLabel->setPixmap(QIcon(buttonIcon).pixmap(16, 16));
  2076. iconLabel->setGeometry(10, 16, 16, 16); // 图标距离左边10px,顶部16px
  2077. iconLabel->setFixedSize(16, 16);
  2078. iconLabel->setStyleSheet("background-color: transparent;");
  2079. iconLabel->setVisible(isEnabled); // 根据按钮的可见性设置图标的可见性
  2080. // 创建文本标签
  2081. QLabel *textLabel = new QLabel(buttonText, button);
  2082. textLabel->setGeometry(34, 0, 90, 48); // 文本距离左边34px
  2083. textLabel->setWordWrap(true); // 允许换行
  2084. textLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
  2085. textLabel->setStyleSheet(R"(
  2086. QLabel {
  2087. background: transparent;
  2088. font-family: "思源黑体";
  2089. font-size: 14px;
  2090. font-weight: 500;
  2091. color: #4E51CE;
  2092. }
  2093. )");
  2094. textLabel->setVisible(isEnabled); // 根据按钮的可见性设置文本的可见性
  2095. // 创建 F1-F12 标签
  2096. QString fLabelText = QString("F%1").arg(i + 1); // F1, F2, ..., F12
  2097. QLabel *fLabel = new QLabel(fLabelText, button);
  2098. fLabel->setFixedSize(21, 16); // 设置大小为21x16
  2099. fLabel->setAlignment(Qt::AlignCenter);
  2100. fLabel->setStyleSheet(R"(
  2101. QLabel {
  2102. background-color: transparent;
  2103. color: #2A7ED8;
  2104. font-size: 12px;
  2105. font-weight: bold;
  2106. }
  2107. )");
  2108. // 设置标签的位置
  2109. int fX = 134;
  2110. int fY = 2;
  2111. fLabel->setGeometry(fX, fY, 14, 16);
  2112. fLabel->setVisible(isEnabled); // 根据按钮的可见性设置标签的可见性
  2113. // 将按钮、图标、文本和标签添加到控件列表
  2114. m_fieldWidgets.append(button);
  2115. m_fieldWidgets.append(iconLabel);
  2116. m_fieldWidgets.append(textLabel);
  2117. m_fieldWidgets.append(fLabel);
  2118. }
  2119. }
  2120. // 清理并隐藏三级目录菜单内容
  2121. void DbTreeViewManager::clearThirdLevelMenu()
  2122. {
  2123. // 遍历所有子控件,找到标题为 "字段展示" 的窗口并关闭
  2124. foreach (QObject *child, widget2->children()) {
  2125. QWidget *childWidget = qobject_cast<QWidget*>(child);
  2126. if (childWidget && childWidget->windowTitle() == "字段展示") {
  2127. qDebug() << "关闭现有的字段展示窗口";
  2128. childWidget->close();
  2129. }
  2130. }
  2131. // 显示主目录树和分隔线
  2132. treeViewDown->show();
  2133. for (auto separator : firstLevelSeparators) {
  2134. separator->show();
  2135. }
  2136. }
  2137. // 保存选中路径
  2138. void DbTreeViewManager::saveCheckedPaths()
  2139. {
  2140. if (m_currentConfigId == -1) {
  2141. qWarning() << "当前配置ID无效,无法保存复选框状态。";
  2142. return;
  2143. }
  2144. QSettings settings("RunCloudTech", "David");
  2145. QString configKey = QString::number(m_currentConfigId);
  2146. settings.beginGroup("TreeViewCheckedState");
  2147. // 保存选中路径
  2148. QString keyChecked = QString("checkedPaths/%1").arg(configKey);
  2149. QStringList checkedList = collectCheckedPaths();
  2150. settings.setValue(keyChecked, checkedList);
  2151. settings.endGroup();
  2152. qDebug() << "保存复选框状态路径:" << checkedList;
  2153. }
  2154. // 加载选中路径
  2155. void DbTreeViewManager::loadCheckedPaths()
  2156. {
  2157. if (m_currentConfigId == -1) {
  2158. qWarning() << "当前配置ID无效,无法加载复选框状态。";
  2159. return;
  2160. }
  2161. QSettings settings("RunCloudTech", "David");
  2162. QString configKey = QString::number(m_currentConfigId);
  2163. settings.beginGroup("TreeViewCheckedState");
  2164. // 读取选中路径
  2165. QString keyChecked = QString("checkedPaths/%1").arg(configKey);
  2166. QStringList loadedChecked = settings.value(keyChecked).toStringList();
  2167. settings.endGroup();
  2168. qDebug() << "加载复选框状态路径:" << loadedChecked;
  2169. m_blockItemChanged = true;
  2170. setCheckedPaths(loadedChecked);
  2171. m_blockItemChanged = false;
  2172. // 更新导航栏
  2173. if (!loadedChecked.isEmpty()) {
  2174. QString lastPathStr = loadedChecked.last();
  2175. QStringList lastPath = lastPathStr.split("/");
  2176. QModelIndex lastIdx = findItemByPath(lastPath);
  2177. if (lastIdx.isValid()) {
  2178. treeViewDown->setCurrentIndex(lastIdx);
  2179. updateNavigationBar(lastIdx);
  2180. }
  2181. } else {
  2182. // 如果没有加载到任何路径,自动选择第一个目录
  2183. QStandardItem *rootItem = model->invisibleRootItem();
  2184. if (rootItem->rowCount() > 0) {
  2185. QModelIndex firstIndex = model->index(0, 0, QModelIndex());
  2186. if (firstIndex.isValid()) {
  2187. treeViewDown->setCurrentIndex(firstIndex);
  2188. treeViewDown->expand(firstIndex); // 展开第一个目录
  2189. QStandardItem *firstItem = model->itemFromIndex(firstIndex);
  2190. QVariant data = firstItem->data(Qt::UserRole + 2);
  2191. if (data.canConvert<QJsonObject>()) {
  2192. QJsonObject thirdLevelObj = data.toJsonObject();
  2193. if (thirdLevelObj.contains("IsThirdLevel") && thirdLevelObj["IsThirdLevel"].toBool()) {
  2194. loadButtonConfigForThirdLevel(thirdLevelObj);
  2195. }
  2196. }
  2197. }
  2198. }
  2199. }
  2200. }
  2201. // 保存展开路径
  2202. void DbTreeViewManager::saveExpandedPaths()
  2203. {
  2204. if (m_currentConfigId == -1) {
  2205. qWarning() << "当前配置ID无效,无法保存展开路径。";
  2206. return;
  2207. }
  2208. QSettings settings("RunCloudTech", "David");
  2209. QString configKey = QString::number(m_currentConfigId);
  2210. settings.beginGroup("TreeViewExpandedState");
  2211. // 保存展开路径
  2212. QString keyExpanded = QString("expandedPaths/%1").arg(configKey);
  2213. QStringList expandedList = QStringList(expandedPaths.begin(), expandedPaths.end());
  2214. settings.setValue(keyExpanded, expandedList);
  2215. settings.endGroup();
  2216. qDebug() << "保存展开路径:" << expandedList;
  2217. }
  2218. // 加载展开路径
  2219. void DbTreeViewManager::loadExpandedPaths()
  2220. {
  2221. if (m_currentConfigId == -1) {
  2222. qWarning() << "当前配置ID无效,无法加载展开路径。";
  2223. return;
  2224. }
  2225. QSettings settings("RunCloudTech", "David");
  2226. QString configKey = QString::number(m_currentConfigId);
  2227. settings.beginGroup("TreeViewExpandedState");
  2228. // 读取展开路径
  2229. QString keyExpanded = QString("expandedPaths/%1").arg(configKey);
  2230. QStringList loadedExpanded = settings.value(keyExpanded).toStringList();
  2231. settings.endGroup();
  2232. qDebug() << "加载展开路径:" << loadedExpanded;
  2233. m_blockItemChanged = true;
  2234. // 恢复展开路径
  2235. for (const QString &p : loadedExpanded) {
  2236. QStringList path = p.split("/");
  2237. QModelIndex idx = findItemByPath(path);
  2238. if (idx.isValid()) {
  2239. treeViewDown->expand(idx);
  2240. expandedPaths.insert(p);
  2241. qDebug() << "成功恢复展开路径:" << p;
  2242. } else {
  2243. qDebug() << "未找到展开路径部分: " << p;
  2244. }
  2245. }
  2246. m_blockItemChanged = false;
  2247. }
  2248. // 清空历史
  2249. void DbTreeViewManager::clearHistory()
  2250. {
  2251. m_backStack.clear();
  2252. m_forwardStack.clear();
  2253. buttonLeft->setIcon(QIcon(":/images/home_left_hide.png"));
  2254. buttonRight->setIcon(QIcon(":/images/home_right.png"));
  2255. }
  2256. // 获取当前页面的 PageState
  2257. DbTreeViewManager::PageState DbTreeViewManager::getCurrentPageState()
  2258. {
  2259. PageState st;
  2260. st.isThirdLevel = false;
  2261. st.directoryId = -1;
  2262. // 判断是否在第三层窗口中
  2263. if (m_thirdLevelFieldWnd && m_thirdLevelFieldWnd->isVisible()) {
  2264. // 如果此时是在第三层界面,则用当前导航栏 or 目录树的 “选中项” 来获取路径
  2265. QModelIndex curIndex = treeViewDown->currentIndex();
  2266. if (!curIndex.isValid()) {
  2267. st.path << "未知目录";
  2268. } else {
  2269. QStandardItem* item = model->itemFromIndex(curIndex);
  2270. st.path = buildItemPath(item);
  2271. }
  2272. // 如果能拿到 DirectoryId,则置为第三层
  2273. QVariant dataVar = model->itemFromIndex(treeViewDown->currentIndex())->data(Qt::UserRole + 2);
  2274. if (dataVar.canConvert<QJsonObject>()) {
  2275. QJsonObject obj = dataVar.toJsonObject();
  2276. if (obj.contains("IsThirdLevel") && obj["IsThirdLevel"].toBool()) {
  2277. st.isThirdLevel = true;
  2278. st.directoryId = obj.value("Id").toInt(-1);
  2279. }
  2280. }
  2281. }
  2282. else {
  2283. // 当前是目录树界面,就看 treeView 选中项
  2284. QModelIndex curIndex = treeViewDown->currentIndex();
  2285. if (curIndex.isValid()) {
  2286. QStandardItem* item = model->itemFromIndex(curIndex);
  2287. st.path = buildItemPath(item);
  2288. // 检查是否第三层
  2289. QVariant dataVar = item->data(Qt::UserRole + 2);
  2290. if (dataVar.canConvert<QJsonObject>()) {
  2291. QJsonObject obj = dataVar.toJsonObject();
  2292. if (obj.contains("IsThirdLevel") && obj["IsThirdLevel"].toBool()) {
  2293. st.isThirdLevel = true;
  2294. st.directoryId = obj.value("Id").toInt(-1);
  2295. }
  2296. }
  2297. }
  2298. }
  2299. return st;
  2300. }
  2301. //加载指定的 PageState:相当于“回到该路径”或“跳转到这个第三层”
  2302. void DbTreeViewManager::loadPageState(const PageState &st, bool isByHistoryNav)
  2303. {
  2304. // 先根据 st.path 找到对应的节点
  2305. QModelIndex idx = findItemByPath(st.path);
  2306. if (!idx.isValid()) {
  2307. qWarning() << "[loadPageState] 未找到路径" << st.path;
  2308. return;
  2309. }
  2310. // 选中该节点
  2311. treeViewDown->setCurrentIndex(idx);
  2312. treeViewDown->scrollTo(idx);
  2313. // 更新导航栏
  2314. updateNavigationBar(idx);
  2315. // 如果是第三层,就加载对应的数据窗口
  2316. if (st.isThirdLevel && st.directoryId != -1) {
  2317. // 如果当前已在一个第三层窗口,先关闭它
  2318. if (m_thirdLevelFieldWnd) {
  2319. m_thirdLevelFieldWnd->close();
  2320. m_thirdLevelFieldWnd->deleteLater();
  2321. m_thirdLevelFieldWnd = nullptr;
  2322. }
  2323. int userPrivilege = 0x1;
  2324. QJsonObject data = fetchThirdLevelData(st.directoryId, userPrivilege);
  2325. displayThirdLevelFields(data, (m_currentConfigId == 1));
  2326. } else {
  2327. // 否则,显示目录树
  2328. if (m_thirdLevelFieldWnd) {
  2329. m_thirdLevelFieldWnd->close();
  2330. m_thirdLevelFieldWnd->deleteLater();
  2331. m_thirdLevelFieldWnd = nullptr;
  2332. }
  2333. treeViewDown->show();
  2334. for (auto sep : firstLevelSeparators) {
  2335. if (sep) sep->show();
  2336. }
  2337. }
  2338. if (!isByHistoryNav) {
  2339. m_forwardStack.clear();
  2340. buttonRight->setIcon(QIcon(":/images/home_right.png"));
  2341. // 把新状态压入后退栈
  2342. m_backStack.append(st);
  2343. if(m_backStack.size() >= 2){
  2344. buttonLeft->setIcon(QIcon(":/images/home_left.png"));
  2345. }
  2346. }
  2347. }