├── COPYING ├── INSTALL ├── README ├── libs └── qjsontreewidget │ ├── qjsonsortfilterproxymodel.cpp │ ├── qjsonsortfilterproxymodel.h │ ├── qjsontree_global.h │ ├── qjsontreeitem.cpp │ ├── qjsontreeitem.h │ ├── qjsontreeitemdelegate.cpp │ ├── qjsontreeitemdelegate.h │ ├── qjsontreemodel.cpp │ ├── qjsontreemodel.h │ ├── qjsontreewidget.cpp │ ├── qjsontreewidget.h │ └── qjsontreewidget.pro └── test ├── dialog.cpp ├── dialog.h ├── dialog.ui ├── main.cpp ├── test.json └── test.pro /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /INSTALL: -------------------------------------------------------------------------------- 1 | QJsonTreeWidget uses QJSon library by Fabio Castelli (http://qjson.sourceforge.net), it must be checkouted in the libs folder 2 | together with the src of qjsontreewidget. 3 | 4 | libs/qjson/ 5 | libs/qjsontreewidget/ 6 | 7 | Then, just open the testqjstw.pro in QtCreator and compile. A test application can be found in /test. 8 | 9 | to deploy, you have to take care yourself of distributing the qjson DLL/.so with your application. 10 | 11 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | QJsonTreeWidget is a QT library which eases the displaying and editing of JSON structured trees. 2 | think of your application configuration data, or generally any other kind of data you need to display using a tree. 3 | 4 | Usage is really simple, you just have to adopt this format for your tree: 5 | 6 | . each line of the JSON file should represent a leaf in your tree (this eases maintenance by hand, but really 7 | you can indent your JSON whatever you prefer), embodied in a JSON object. 8 | 9 | . each leaf should have at least a '_desc_' and a 'name' node (not mandatory). if it's a parent node, it must have a '_children_' JSON node. 10 | 11 | . the root JSON object must have a 'version' node (to support versioning) and a '_headers_' node'. 12 | format of the _headers_ node is 13 | 14 | this tells QJSonTreeWidget to display each node named in a column with header named at 15 | index . 16 | the optional parameter is for columns where you need a custom painted widget (not an editor), such as a button. 17 | 18 | . each leaf can have one or more widgets to be displayed, actually QJsonTreeWidget supports, as editors, 19 | QLineEdit, QSpinBox, QCheckBox and QComboBox. As static widgets, QPushButton. 20 | subtrees having not having "_children_" (empty parents) should have a "_widget_:something": "Tree" set, to recognize them as parents. 21 | 22 | format is i.e. "_widget_:JSONtag": "QLineEdit", which displays a QLineEdit for the JSON node named . 23 | 24 | . to display an editor widget, use something like : 25 | "value": yourvalue, "_widget_:value": "QLineEdit" 26 | 27 | to display a static widget: 28 | "button1": "QPushButton,,buttontext,,pixmap" 29 | where pixmap is a 16x16 icon stored in your resources (i.e. :/images/pixmaps/icon.png). 30 | both icon and text can be present, or just one (i.e. QPushButton,,,,pixmap for no text and icon) 31 | 32 | . every leaf can have a '_hide_' parameter, which hides the whole leaf from displaying. 33 | moreover, if you use '_hide_:JSONtag' you can selectively hide only the node named . 34 | 35 | . every leaf can have optional '_readonly_:JSONtag' to selectively display node as readonly. 36 | 37 | . a parent leaf can have an optional '_template_' bool node. if this is set, the leaf is used as a template leaf 38 | (hidden from display), which means the user can right-click on the leaf to create/delete child leafs of the same type. 39 | 40 | moreover, if the template leaf has '_mandatory_' bool node set, at least one leaf of this kind must exist in the 41 | JSON (it can't be removed by the user) 42 | 43 | . each widget have its own options, using the format "_option_:JSONtag", which means 'apply this option to the node 44 | named '. supported options are: 45 | 46 | QLineEdit: '_regexp_' to set a regular expression validator on the editor. 47 | QSpinBox: '_valuemax_' and '_valuemin_' to set min/max limits of the spinbox. 48 | QComboBox: '_valuelist_' to set the possible combobox values. 49 | 50 | . the tree can be sorted using the setSortingEnabled(), setSortOrder() and setDynamicSortFiltering of QJsonTreeWidget. 51 | 52 | . the tree can be exported to QVariantMap, QByteArray JSON, QIODevice using the saveJson() function 53 | 54 | . when exporting, you can set the tree to purge JSON tags by using the setPurgeListOnSave() function 55 | 56 | . right clicking on the header let you access the sort and save popup menu 57 | 58 | . search can be performed on the tree using the search() function. You can advance to the next item in the search using F3. 59 | 60 | . using CTRL-C you can copy the selected item text to the clipboard. 61 | 62 | a sample 'test.json' is included in the package. 63 | 64 | have fun, 65 | valerino 66 | 67 | -------------------------------------------------------------------------------- /libs/qjsontreewidget/qjsonsortfilterproxymodel.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of QJsonTreeWidget. 3 | 4 | Copyright (C) 2012 valerino 5 | 6 | QJsonTreeWidget is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | QJsonTreeWidget is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with QJsonTreeWidget. If not, see . 18 | */ 19 | #include "qjsonsortfilterproxymodel.h" 20 | 21 | QJsonSortFilterProxyModel::QJsonSortFilterProxyModel(QObject *parent) : 22 | QSortFilterProxyModel(parent) 23 | { 24 | } 25 | 26 | QJsonSortFilterProxyModel::~QJsonSortFilterProxyModel() 27 | { 28 | } 29 | 30 | bool QJsonSortFilterProxyModel::filterAcceptsRow ( int source_row, const QModelIndex & source_parent ) const 31 | { 32 | if (!source_parent.isValid()) 33 | return true; 34 | 35 | const QJsonTreeModel* model = static_cast(source_parent.model()); 36 | QJsonTreeItem* item = model->itemByModelIndex(source_parent)->child(source_row); 37 | int flags = model->specialFlags(); 38 | if (item->map().contains("_template_")) 39 | return false; 40 | 41 | bool roset = item->map().value("__hasROSet__",false).toBool(); 42 | if (roset && (flags & QJsonTreeItem::ReadOnlyHidesRow) && (flags & QJsonTreeItem::HonorHide)) 43 | return false; 44 | 45 | bool hide = item->map().value("_hide_",false).toBool(); 46 | if (hide && (flags & QJsonTreeItem::HonorHide)) 47 | return false; 48 | 49 | // check regexp on each column 50 | if (this->filterRegExp().isEmpty()) 51 | return true; 52 | int cols = item->columnCount(); 53 | for (int i=0; i < cols; i++) 54 | { 55 | // select ? 56 | if (item->text(i).contains(this->filterRegExp())) 57 | { 58 | QModelIndex mi = this->mapFromSource(model->indexByItem(item,i)); 59 | item->view()->selectionModel()->select(mi,QItemSelectionModel::Select); 60 | } 61 | } 62 | return true; 63 | } 64 | 65 | QModelIndex QJsonSortFilterProxyModel::indexToSourceIndex (const QModelIndex& index) 66 | { 67 | if (!index.isValid()) 68 | return QModelIndex(); 69 | return static_cast(index.model())->mapToSource(index); 70 | } 71 | 72 | QModelIndex QJsonSortFilterProxyModel::indexToProxyIndex (const QModelIndex& index) 73 | { 74 | if (!index.isValid()) 75 | return QModelIndex(); 76 | return static_cast(index.model())->mapFromSource(index); 77 | } 78 | 79 | const QJsonTreeModel* QJsonSortFilterProxyModel::indexSourceModel (const QModelIndex& index) 80 | { 81 | if (!index.isValid()) 82 | return 0; 83 | 84 | const QJsonSortFilterProxyModel* m = static_cast (index.model()); 85 | return static_cast(m->sourceModel()); 86 | } 87 | -------------------------------------------------------------------------------- /libs/qjsontreewidget/qjsonsortfilterproxymodel.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of QJsonTreeWidget. 3 | 4 | Copyright (C) 2012 valerino 5 | 6 | QJsonTreeWidget is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | QJsonTreeWidget is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with QJsonTreeWidget. If not, see . 18 | */ 19 | 20 | #ifndef QJSONSORTFILTERPROXYMODEL_H 21 | #define QJSONSORTFILTERPROXYMODEL_H 22 | 23 | #include 24 | #include 25 | #include "qjsontreemodel.h" 26 | #include "qjsontreeitem.h" 27 | 28 | class QJsonSortFilterProxyModel : public QSortFilterProxyModel 29 | { 30 | friend class QJsonTreeModel; 31 | friend class QJsonTreeItem; 32 | Q_OBJECT 33 | protected: 34 | /** 35 | * @brief reimplementation of filterAcceptsRow() from the QSortFilterProxyModel interface 36 | * 37 | * @param source_row the row index in the source model 38 | * @param source_parent the parent model index 39 | * @return bool 40 | */ 41 | virtual bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const; 42 | 43 | public: 44 | /** 45 | * @brief constructor 46 | * 47 | * @param parent the parent object (optional) 48 | */ 49 | explicit QJsonSortFilterProxyModel(QObject *parent = 0); 50 | 51 | /** 52 | * @brief destructor 53 | * 54 | */ 55 | virtual ~QJsonSortFilterProxyModel(); 56 | 57 | /** 58 | * @brief helper function to map an index to the source model index (calls mapToSource() on the index model) 59 | * 60 | * @param index must be a valid proxy model index 61 | * @return QModelIndex 62 | */ 63 | static QModelIndex indexToSourceIndex (const QModelIndex& index); 64 | 65 | /** 66 | * @brief helper function to map an index to the proxy model index (calls mapToSource() on the index model) 67 | * 68 | * @param index must be a valid source model index 69 | * @return QModelIndex 70 | */ 71 | static QModelIndex indexToProxyIndex (const QModelIndex& index); 72 | 73 | /** 74 | * @brief helper function to retrieve the index source model 75 | * 76 | * @param index must be a valid proxy model index 77 | * @return const QJsonTreeModel* 78 | */ 79 | static const QJsonTreeModel* indexSourceModel (const QModelIndex& index); 80 | 81 | }; 82 | 83 | #endif // QJSONSORTFILTERPROXYMODEL_H 84 | -------------------------------------------------------------------------------- /libs/qjsontreewidget/qjsontree_global.h: -------------------------------------------------------------------------------- 1 | #ifndef QJSONTREE_GLOBAL_H 2 | #define QJSONTREE_GLOBAL_H 3 | 4 | #include 5 | 6 | #if defined(QJSONTREE_LIBRARY) 7 | # define QJSONTREE_EXPORT Q_DECL_EXPORT 8 | #else 9 | # define QJSONTREE_EXPORT Q_DECL_IMPORT 10 | #endif 11 | 12 | #endif // QJSONTREE_GLOBAL_H 13 | -------------------------------------------------------------------------------- /libs/qjsontreewidget/qjsontreeitem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of QJsonTreeWidget. 3 | 4 | Copyright (C) 2012 valerino 5 | 6 | QJsonTreeWidget is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | QJsonTreeWidget is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with QJsonTreeWidget. If not, see . 18 | */ 19 | 20 | #include "qjsontreeitem.h" 21 | #include "qjsontreewidget.h" 22 | 23 | QHash QJsonTreeItem::widgetFlags; 24 | QStringList QJsonTreeItem::descriptiveTags; 25 | 26 | QJsonTreeItem::QJsonTreeItem (QJsonTreeWidget* tree, QJsonTreeItem *parent, const QVariantMap &map, bool ignoreheaders) 27 | { 28 | m_headersCount = 0; 29 | m_widget = 0; 30 | m_error = QJsonTreeItem::JsonNoError; 31 | m_parent = parent; 32 | m_widget = tree; 33 | m_map = map; 34 | m_backgroundColor = QColor(); 35 | m_foregroundColor = QColor(); 36 | m_font = QFont(); 37 | m_fontValid = false; 38 | m_children = QList(); 39 | 40 | // this is done only once 41 | if (QJsonTreeItem::widgetFlags.isEmpty()) 42 | QJsonTreeItem::buildWidgetFlags(); 43 | if (QJsonTreeItem::descriptiveTags.isEmpty()) 44 | QJsonTreeItem::buildDescriptiveTags(); 45 | 46 | // just create an empty item ? 47 | if (map.isEmpty()) 48 | return; 49 | 50 | // create item from map 51 | fromMap(map,parent,ignoreheaders); 52 | } 53 | 54 | bool QJsonTreeItem::fromMap(const QVariantMap &map, QJsonTreeItem *parent,bool ignoreheaders) 55 | { 56 | m_parent = parent; 57 | m_map = map; 58 | 59 | if (parent == 0) 60 | { 61 | m_root = this; 62 | 63 | // this is the root item, must have "_headers_" set, store headers descriptor in m_headers 64 | if (!setColumnHeaders(map.value("_headers_",QString()).toString()) && !ignoreheaders) 65 | { 66 | m_error = QJsonTreeItem::JsonMissingOrInvalidHeaders; 67 | m_invalidMap = m_map; 68 | 69 | // this invalidates the root map too 70 | m_root->m_error = m_error; 71 | m_root->m_invalidMap = m_invalidMap; 72 | return false; 73 | } 74 | } 75 | else 76 | { 77 | m_headers = parent->headers(); 78 | m_root = parent->rootItem(); 79 | m_headersCount = parent->columnCount(); 80 | m_totalTreeItems = parent->totalTreeItems(); 81 | } 82 | 83 | // this is to optimize model index() function 84 | foreach (QString k, m_map.keys()) 85 | { 86 | if (k.contains("_readonly_")) 87 | { 88 | // add this value, this will be checked for special flag ReadOnlyHidesRow 89 | m_map["__hasROSet__"] = m_map[k]; 90 | break; 91 | } 92 | } 93 | 94 | if (m_map.contains("_children_")) 95 | { 96 | QVariantList l = m_map["_children_"].toList(); 97 | foreach (QVariant mm, l) 98 | { 99 | // recurse 100 | QJsonTreeItem* i = new QJsonTreeItem(this->widget(),this,mm.toMap()); 101 | this->appendChild(i); 102 | } 103 | } 104 | 105 | // strip "_children_" (to not waste memory, on save we use the tree structure to regenerate it) 106 | m_map.remove("_children_"); 107 | m_error = QJsonTreeItem::JsonNoError; 108 | 109 | return true; 110 | } 111 | 112 | QJsonTreeItem::~QJsonTreeItem() 113 | { 114 | this->clear(); 115 | } 116 | 117 | void QJsonTreeItem::appendChild(QJsonTreeItem *child) 118 | { 119 | m_children.append(child); 120 | m_root->m_totalTreeItems++; 121 | } 122 | 123 | void QJsonTreeItem::removeChild(int row) 124 | { 125 | QJsonTreeItem* it = this->child(row); 126 | m_children.removeAt(row); 127 | delete it; 128 | m_root->m_totalTreeItems--; 129 | } 130 | 131 | int QJsonTreeItem::totalChildCount() const 132 | { 133 | int rowabs = this->rowAbsolute(); 134 | return (m_root->m_totalTreeItems - rowabs); 135 | } 136 | 137 | bool QJsonTreeItem::setColumnHeaders (const QString& columns) 138 | { 139 | m_headers.clear(); 140 | 141 | // split columns string 142 | QStringList l = columns.split(","); 143 | if (l.isEmpty()) 144 | { 145 | // something wrong, "_headers_" empty/missing 146 | return false; 147 | } 148 | m_headersCount = l.count(); 149 | 150 | foreach (QString s, l) 151 | { 152 | QStringList sl = s.split(":"); 153 | QHash h; 154 | 155 | if (sl.count() < 3) 156 | { 157 | // something wrong in the "_headers_" tag, 158 | return false; 159 | } 160 | 161 | // save name, jsontag and header idx in an hash 162 | h["__name__"]=sl.at(0); 163 | h["__tag__"]=sl.at(1); 164 | h["__idx__"]=sl.at(2).toInt(); 165 | if (sl.count() == 4) 166 | { 167 | // this column item need to be drawn. there must be an option at the corresponding item map with i.e. tag=QPushButton,buttontext 168 | h["__draw__"]=(sl.at(3).compare("draw",Qt::CaseInsensitive) == 0) ? true:false; 169 | } 170 | 171 | // use the same values as keys in the parent hash 172 | m_headers[sl.at(0)] = h; 173 | m_headers[sl.at(1)] = h; 174 | m_headers[sl.at(2)] = h; 175 | } 176 | return true; 177 | } 178 | 179 | const QString QJsonTreeItem::headerNameOrTagByInt(int column, bool returntag) const 180 | { 181 | QHash h = headerHashByIdx(column); 182 | if (h.isEmpty()) 183 | return QString(); 184 | 185 | if (returntag) 186 | return h["__tag__"].toString(); 187 | return h["__name__"].toString(); 188 | } 189 | 190 | const QString QJsonTreeItem::headerNameOrTagByString (const QString &name, bool returntag, int* column) const 191 | { 192 | if (column) 193 | *column = -1; 194 | 195 | QHash h = headerHashByName(name); 196 | if (h.isEmpty()) 197 | return QString(); 198 | 199 | if (column) 200 | *column = h["__idx__"].toInt(); 201 | 202 | if (returntag) 203 | return h["__tag__"].toString(); 204 | return h["__name__"].toString(); 205 | } 206 | 207 | const QString QJsonTreeItem::headerTagByIdx(int column) const 208 | { 209 | return headerNameOrTagByInt(column,true); 210 | } 211 | 212 | const QString QJsonTreeItem::headerTagByName(const QString &name, int* column) const 213 | { 214 | return headerNameOrTagByString(name,true,column); 215 | } 216 | 217 | const QString QJsonTreeItem::headerNameByIdx(int column) const 218 | { 219 | return headerNameOrTagByInt(column,false); 220 | } 221 | 222 | const QString QJsonTreeItem::headerNameByTag(const QString &tag, int *column) const 223 | { 224 | return headerNameOrTagByString(tag,false,column); 225 | } 226 | 227 | int QJsonTreeItem::headerIdxByTag(const QString &tag) const 228 | { 229 | QHash h = m_headers.value(tag,QHash()); 230 | if (h.isEmpty()) 231 | return -1; 232 | return h["__idx__"].toInt(); 233 | } 234 | 235 | int QJsonTreeItem::headerIdxByName(const QString &name) const 236 | { 237 | return headerIdxByTag(name); // since we have the name too as key in the parent hash, this will work 238 | } 239 | 240 | QString QJsonTreeItem::text(int column) const 241 | { 242 | QString tag = headerTagByIdx(column); 243 | return m_map.value(tag,QString()).toString(); 244 | } 245 | 246 | bool QJsonTreeItem::validateRegexp(QString* nonmatchingcol, QString* nonmatchingname, QString* nonmatchingval) const 247 | { 248 | for (int i=0; i < this->columnCount(); i++) 249 | { 250 | // check if we have a regexp set 251 | QString tag = headerTagByIdx(i); 252 | QRegExp rx = QRegExp(m_map.value("_regexp_:" % tag,QString()).toString()); 253 | if (rx.isEmpty()) 254 | continue; 255 | 256 | QString val = m_map.value(tag,QString()).toString(); 257 | if (!rx.exactMatch(val)) 258 | { 259 | *nonmatchingcol = headerNameByIdx(i); 260 | *nonmatchingname = m_map.value("name",QString()).toString(); 261 | *nonmatchingval = val; 262 | return false; 263 | } 264 | } 265 | return true; 266 | } 267 | 268 | bool QJsonTreeItem::isTree() const 269 | { 270 | foreach (QString k, m_map.keys()) 271 | { 272 | if (k.contains("_widget_:")) 273 | { 274 | if (m_map[k].toString().compare("Tree",Qt::CaseInsensitive) == 0) 275 | return true; 276 | } 277 | } 278 | return false; 279 | } 280 | 281 | int QJsonTreeItem::depth() const 282 | { 283 | int d = 0; 284 | const QJsonTreeItem* it = this; 285 | while (it->hasParent()) 286 | { 287 | d++; 288 | it = it->parent(); 289 | } 290 | return d; 291 | } 292 | 293 | int QJsonTreeItem::row() const 294 | { 295 | // if there's a parent item, this item's corresponding row is taken from the childs index of its parent. either, its the 1st row (row 0, this is a parent item) 296 | QJsonTreeItem* parent = this->parent(); 297 | if (parent) 298 | return (parent->children().indexOf(const_cast(this))); 299 | return 0; 300 | } 301 | 302 | int QJsonTreeItem::rowAbsolute() const 303 | { 304 | if (!this->parent()) 305 | { 306 | // this is the tree root item, row 0 307 | return 0; 308 | } 309 | 310 | // this item relative row 311 | int n = row(); 312 | QJsonTreeItem* parent = this->parent()->parent(); 313 | while (parent) 314 | { 315 | // add this parent's parent childs 316 | n+=parent->childCount(); 317 | parent = parent->parent(); 318 | } 319 | return n; 320 | } 321 | 322 | void QJsonTreeItem::clear() 323 | { 324 | qDeleteAll(m_children); 325 | m_children.clear(); 326 | } 327 | 328 | void QJsonTreeItem::buildWidgetFlags() 329 | { 330 | // populate the hash with flags appropriate for the item, this will be read by the model 331 | QJsonTreeItem::widgetFlags["Tree"] = (Qt::NoItemFlags); 332 | QJsonTreeItem::widgetFlags["QCheckBox"]=(Qt::ItemIsEditable|Qt::ItemIsUserCheckable); 333 | QJsonTreeItem::widgetFlags["QComboBox"]=(Qt::ItemIsEditable); 334 | QJsonTreeItem::widgetFlags["QLineEdit"]=(Qt::ItemIsEditable); 335 | QJsonTreeItem::widgetFlags["QPushButton"]= (Qt::NoItemFlags); 336 | QJsonTreeItem::widgetFlags["QSpinBox"]=(Qt::ItemIsEditable); 337 | } 338 | 339 | void QJsonTreeItem::buildDescriptiveTags() 340 | { 341 | // populate the list with descriptive tags 342 | QJsonTreeItem::descriptiveTags.append("_widget_"); 343 | QJsonTreeItem::descriptiveTags.append("_headers_"); 344 | QJsonTreeItem::descriptiveTags.append("_desc_"); 345 | QJsonTreeItem::descriptiveTags.append("_valuemin_"); 346 | QJsonTreeItem::descriptiveTags.append("_valuemax_"); 347 | QJsonTreeItem::descriptiveTags.append("_valuelist_"); 348 | QJsonTreeItem::descriptiveTags.append("_regexp_"); 349 | QJsonTreeItem::descriptiveTags.append("_readonly_"); 350 | QJsonTreeItem::descriptiveTags.append("_hide_"); 351 | QJsonTreeItem::descriptiveTags.append("_template_"); 352 | QJsonTreeItem::descriptiveTags.append("_mandatory_"); 353 | } 354 | 355 | void QJsonTreeItem::setMapValue(int column, const QVariant &value) 356 | { 357 | QString tag = headerTagByIdx(column); 358 | setMapValue(tag,value); 359 | } 360 | 361 | QVariantMap QJsonTreeItem::toMap(int depth, QVariantMap intmap, QJsonTreeItem* item) const 362 | { 363 | const QJsonTreeItem* it; 364 | if (depth == 0) 365 | { 366 | // first call 367 | intmap = m_map; 368 | it = this; 369 | } 370 | else 371 | { 372 | it = item; 373 | intmap = it->map(); 374 | } 375 | 376 | // this was added for optimization when building the tree 377 | intmap.remove("__hasROSet__"); 378 | bool returnempty = false; 379 | 380 | // check items to be purged 381 | QHash purgelist = it->widget()->purgeListOnSave(); 382 | if (!purgelist.isEmpty()) 383 | { 384 | foreach (QString k, intmap.keys()) 385 | { 386 | if (purgelist.contains(k)) 387 | { 388 | if (purgelist.value(k,false) == true) 389 | { 390 | // strip the item completely 391 | returnempty = true; 392 | } 393 | else 394 | { 395 | // just remove the tag 396 | intmap.remove(k); 397 | } 398 | } 399 | } 400 | } 401 | if (returnempty) 402 | return QVariantMap(); 403 | 404 | // strip descriptive tags ? 405 | QVariantMap newmap = intmap; 406 | if (it->widget()->purgeDescriptiveTags()) 407 | { 408 | foreach (QString k, QJsonTreeItem::descriptiveTags) 409 | { 410 | foreach (QString kk, intmap.keys()) 411 | { 412 | if (kk.startsWith(k,Qt::CaseInsensitive)) 413 | { 414 | newmap.remove(kk); 415 | } 416 | } 417 | } 418 | } 419 | intmap = newmap; 420 | 421 | if (it->childCount() > 0) 422 | { 423 | QVariantList l; 424 | foreach (QJsonTreeItem* i, it->children()) 425 | { 426 | // recurse 427 | depth++; 428 | QVariantMap mm = i->toMap(depth,intmap,i); 429 | if (!mm.isEmpty()) 430 | { 431 | l.append(mm); 432 | } 433 | depth--; 434 | } 435 | 436 | // add list as child 437 | intmap["_children_"] = l; 438 | } 439 | 440 | return intmap; 441 | } 442 | 443 | QJsonTreeModel* QJsonTreeItem::model() 444 | { 445 | return m_widget->model(); 446 | } 447 | 448 | QTreeView* QJsonTreeItem::view() 449 | { 450 | return m_widget->view(); 451 | } 452 | -------------------------------------------------------------------------------- /libs/qjsontreewidget/qjsontreeitem.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of QJsonTreeWidget. 3 | 4 | Copyright (C) 2012 valerino 5 | 6 | QJsonTreeWidget is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | QJsonTreeWidget is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with QJsonTreeWidget. If not, see . 18 | */ 19 | 20 | #ifndef QJSONTREEITEM_H 21 | #define QJSONTREEITEM_H 22 | 23 | #include 24 | #include 25 | #include 26 | #include "qjsontree_global.h" 27 | 28 | class QJsonTreeModel; 29 | class QJsonTreeWidget; 30 | class QTreeView; 31 | class QJsonSortFilterProxyModel; 32 | class QJsonTreeItemDelegate; 33 | 34 | /** 35 | * @brief class to represent a tree item from a JSON object coming from QJsonTreeModel 36 | * 37 | */ 38 | class QJSONTREE_EXPORT QJsonTreeItem 39 | { 40 | friend class QJsonTreeModel; 41 | friend class QJsonTreeWidget; 42 | friend class QJsonSortFilterProxyModel; 43 | friend class QJsonTreeItemDelegate; 44 | 45 | public: 46 | 47 | /** 48 | * @brief internal errors returned when building a QJsonTreeItem 49 | * 50 | */ 51 | enum JsonMapErrors { 52 | JsonNoError = 0, 53 | JsonInvalidMap = 1, 54 | JsonMissingOrInvalidHeaders = 2 55 | }; 56 | 57 | /** 58 | * @brief various item special flags 59 | * 60 | */ 61 | enum SpecialFlag { 62 | HonorReadOnly = 1, 63 | HonorHide = 2, 64 | ReadOnlyHidesRow = 4, 65 | HonorItemBackgroundColor = 8, 66 | HonorItemForegroundColor = 16, 67 | HonorItemFont = 32, 68 | HonorParentsBackgroundColor = 64, 69 | HonorParentsForegroundColor = 128, 70 | HonorParentsFont = 256, 71 | HonorChildsBackgroundColor = 512, 72 | HonorChildsForegroundColor = 1024, 73 | HonorChildsFont = 2048, 74 | HonorColumnBackgroundColor = 4096, 75 | HonorColumnForegroundColor = 8192, 76 | HonorColumnFont = 16384, 77 | HonorAll = HonorReadOnly | HonorHide | HonorItemBackgroundColor | HonorItemForegroundColor | HonorItemFont | HonorParentsBackgroundColor | HonorParentsForegroundColor | HonorParentsFont | 78 | HonorChildsBackgroundColor | HonorChildsForegroundColor | HonorChildsFont | HonorColumnBackgroundColor | HonorColumnForegroundColor | HonorColumnFont 79 | }; 80 | Q_DECLARE_FLAGS (SpecialFlags, SpecialFlag) 81 | 82 | /** 83 | * @brief constructor 84 | * 85 | * @param tree : the QJsonTreeWidget this item belongs to 86 | * @param parent : the item parent (optional) 87 | * @param map: the item data as a map coming from QJson (optional) 88 | * @param ignoreheaders: set to true if you're constructing a spare item (to not be connected to a tree) 89 | */ 90 | QJsonTreeItem (QJsonTreeWidget* tree, QJsonTreeItem *parent = 0, const QVariantMap &map = QVariantMap(), bool ignoreheaders=false); 91 | 92 | /** 93 | * @brief fills an item from a QJson map, replacing previous content 94 | * 95 | * @param map: the item data as a map coming from QJson 96 | * @param parent : the item parent (optional) 97 | * @param ignoreheaders: set to true if you're constructing a spare item (to not be connected to a tree) 98 | * @return bool 99 | */ 100 | bool fromMap(const QVariantMap &map, QJsonTreeItem *parent = 0, bool ignoreheaders=false); 101 | 102 | /** 103 | * @brief destructor 104 | * 105 | */ 106 | virtual ~QJsonTreeItem(); 107 | 108 | /** 109 | * @brief adds a child node to this item 110 | * 111 | * @param child the child item 112 | */ 113 | void appendChild(QJsonTreeItem *child); 114 | 115 | /** 116 | * @brief returns the item at the specified row in the tree view 117 | * 118 | * @param row the row number 119 | * @return QJsonTreeItem 120 | */ 121 | QJsonTreeItem* child(int row) const { return m_children.value(row); } 122 | 123 | /** 124 | * @brief removes the specified child from the internal list. the corresponding QJsonTreeItem* is deleted too. 125 | * 126 | * @param row the row number (= the nth child) 127 | */ 128 | void removeChild (int row); 129 | 130 | /** 131 | * @brief returns this item's children 132 | * 133 | * @return QList 134 | */ 135 | QList children() const { return m_children; } 136 | 137 | /** 138 | * @brief returns whether this item has children or not 139 | * 140 | * @return bool 141 | */ 142 | bool hasChildren() const { return !m_children.isEmpty(); } 143 | 144 | /** 145 | * @brief returns the number of childs this item has (= the number of rows for the parent item) 146 | * 147 | * @return int 148 | */ 149 | int childCount() const { return m_children.count(); } 150 | 151 | /** 152 | * @brief returns the number of childs (recursive) this item has 153 | * 154 | * @return int 155 | */ 156 | int totalChildCount() const; 157 | 158 | /** 159 | * @brief get the total number of items the root item has 160 | * 161 | * return int 162 | */ 163 | int totalTreeItems() const { return m_root->m_totalTreeItems; } 164 | 165 | /** 166 | * @brief returns the number of tree columns this item is represented on (fixed, from JSON root map "_headers_" stored in the root item's columns descriptor) 167 | * 168 | * @return int 169 | */ 170 | int columnCount() const { return m_headersCount; } 171 | 172 | /** 173 | * @brief returns columns description (with name,jsontag,idx). 174 | * Note that this always returns a pointer to rootitem's headers descriptor (m_headers), since this is stored in the root only for optimization 175 | * 176 | * @return QList > 177 | */ 178 | const QHash > headers() const { return m_headers; } 179 | 180 | /** 181 | * @brief sets the whole internal item map for this item (replace the JSON object) 182 | * 183 | * @param map the new item map 184 | */ 185 | void setMap (const QVariantMap& map) { m_map = map; } 186 | 187 | /** 188 | * @brief returns the whole internal map for this item 189 | * 190 | */ 191 | const QVariantMap map() const { return m_map; } 192 | 193 | /** 194 | * @brief sets a new value in the internal item map 195 | * 196 | * @param tag the JSON tag name 197 | * @param value the new value 198 | * @param applyto parameter for the tag (optional) 199 | */ 200 | void setMapValue (const QString& tag, const QVariant& value) { m_map[tag] = value;} 201 | 202 | /** 203 | * @brief sets a new value in the internal item map 204 | * 205 | * @param int the header column index 206 | * @param value the new value 207 | * @param applyto parameter for the tag (optional) 208 | */ 209 | void setMapValue (int column, const QVariant& value); 210 | 211 | /** 212 | * @brief recursively rebuilds the JSON map from the tree structure 213 | * 214 | * @param depth internal (always 0) 215 | * @param intmap internal (always 0) 216 | * @param item internal (always 0) 217 | * @return QVariantMap 218 | */ 219 | QVariantMap toMap(int depth=0, QVariantMap intmap = QVariantMap(), QJsonTreeItem* item = 0) const; 220 | 221 | /** 222 | * @brief returns the row at which this item is in the tree view, relative to its parent if any 223 | * 224 | * @return int 225 | */ 226 | int row() const; 227 | 228 | /** 229 | * @brief returns the row at which this item is in the tree view, relative to the main root item 230 | * 231 | * @return int 232 | */ 233 | int rowAbsolute() const; 234 | 235 | /** 236 | * @brief returns this item's parent 237 | * 238 | * @return QJsonTreeItem 239 | */ 240 | QJsonTreeItem* parent() const { return m_parent; } 241 | 242 | /** 243 | * @brief returns whether this item has parent or not (if not, this is the root item) 244 | * 245 | * @return bool 246 | */ 247 | bool hasParent() const { return (m_parent == 0 ? false : true); } 248 | 249 | /** 250 | * @brief returns the tree root item 251 | * 252 | * @return QJsonTreeItem 253 | */ 254 | QJsonTreeItem* rootItem() const { return m_root; } 255 | 256 | /** 257 | * @brief returns wether the item has been constructed succesfully or not 258 | * 259 | * @return bool 260 | */ 261 | bool isValid() const { return (m_error == QJsonTreeItem::JsonNoError); } 262 | 263 | /** 264 | * @brief returns an error defined in JsonMapErrors 265 | * 266 | * @return JsonMapErrors 267 | */ 268 | QJsonTreeItem::JsonMapErrors error() const { return m_error; } 269 | 270 | /** 271 | * @brief this is a convenience function which returns the map causing the error. 272 | * this will be useful usually only through rootItem()->invalidMap() in case of error during loadJson() from the model 273 | * 274 | * @return QVariantMap 275 | */ 276 | QVariantMap invalidMap() const { return m_invalidMap; } 277 | 278 | /** 279 | * @brief completely clears the item deleting all its child items too. The item can then be reused by calling fromMap() 280 | * 281 | */ 282 | void clear(); 283 | 284 | /** 285 | * @brief returns the QJsonTreeWidget this item belongs to 286 | * 287 | * @return QJsonTreeWidget 288 | */ 289 | QJsonTreeWidget* widget() const { return m_widget; } 290 | 291 | /** 292 | * @brief returns the text at the specified column 293 | * 294 | * @param idx the column index 295 | * @return QString 296 | */ 297 | QString text(int column) const; 298 | 299 | /** 300 | * @brief returns true if all the _regexp_ defined in the item's map matches their assigned values, or false if it doesnt. 301 | * it's valid only for items representing one or more QLineEdit and having one or more regexps set. if not, it returns true as default 302 | * 303 | * @param nonmatchingcol on false return, name of the first nonmatching column 304 | * @param nonmatchingname on false return, name of the first nonmatching name 305 | * @param nonmatchingval on false return, name of the first nonmatching value 306 | * @return bool 307 | */ 308 | bool validateRegexp(QString* nonmatchingcol, QString* nonmatchingname, QString* nonmatchingval) const; 309 | 310 | /** 311 | * @brief sets the background color for the item 312 | * 313 | * @param color the color to be set 314 | */ 315 | void setBackgroundColor(const QColor& color) { m_backgroundColor = color; } 316 | 317 | /** 318 | * @brief returns the background color set for the item, if any 319 | * 320 | * @return QColor 321 | */ 322 | QColor backgroundColor() const { return m_backgroundColor; } 323 | 324 | /** 325 | * @brief sets the foreground color for the item 326 | * 327 | * @param color the color to be set 328 | */ 329 | void setForegroundColor (const QColor& color) {m_foregroundColor = color; } 330 | 331 | /** 332 | * @brief returns the foreground color set for the item, if any 333 | * 334 | * @return QColor 335 | */ 336 | QColor foregroundColor () const { return m_foregroundColor; } 337 | 338 | /** 339 | * @brief sets the font for the item 340 | * 341 | * @param font the font to be set 342 | */ 343 | void setFont (const QFont& font) { m_font = font; m_fontValid = true;} 344 | 345 | /** 346 | * @brief returns the font set for the item, if any 347 | * 348 | * @return QFont 349 | */ 350 | QFont font() const { return m_font; } 351 | 352 | /** 353 | * @brief use this instead of hasChildren, for parents with no childrens 354 | * 355 | * @return bool 356 | */ 357 | bool isTree() const; 358 | 359 | /** 360 | * @brief returns if the item has an initialized font set 361 | * 362 | * @return bool 363 | */ 364 | bool isFontValid() const { return m_fontValid; } 365 | 366 | /** 367 | * @brief returns the item depth (0 for parents) 368 | * 369 | * @return int 370 | */ 371 | int depth() const; 372 | 373 | protected: 374 | QJsonTreeModel* model(); 375 | QTreeView *view(); 376 | 377 | private: 378 | static void buildWidgetFlags(); 379 | static void buildDescriptiveTags(); 380 | bool setColumnHeaders(const QString &headers); 381 | const QString headerNameOrTagByString(const QString &name, bool returntag, int *column) const; 382 | const QString headerNameOrTagByInt(int column, bool returntag) const; 383 | const QString headerNameByIdx(int column) const; 384 | const QString headerNameByTag (const QString& tag, int* column=0) const; 385 | const QString headerTagByIdx (int column) const; 386 | const QString headerTagByName (const QString& name, int* column=0) const; 387 | int headerIdxByTag(const QString &tag) const; 388 | int headerIdxByName(const QString &name) const; 389 | const QHash headerHashByIdx (int column) const { return m_headers.value(QVariant(column).toString(),QHash()); } 390 | const QHash headerHashByTag (const QString& tag) const { return m_headers.value(tag,QHash()); } 391 | const QHash headerHashByName (const QString& name) const { return m_headers.value(name,QHash()); } 392 | static QHash widgetFlags; 393 | static QStringList descriptiveTags; 394 | QJsonTreeItem::JsonMapErrors m_error; 395 | QModelIndex m_index; 396 | QList m_children; 397 | QVariantMap m_map; 398 | QVariantMap m_invalidMap; 399 | QJsonTreeItem* m_parent; 400 | QJsonTreeItem* m_root; 401 | QJsonTreeWidget* m_widget; 402 | QColor m_backgroundColor; 403 | QColor m_foregroundColor; 404 | QFont m_font; 405 | bool m_fontValid; 406 | int m_headersCount; // m_headers.count() to return number of columns wouldnt work, since how we store data in such hash 407 | int m_totalTreeItems; 408 | QHash > m_headers; 409 | }; 410 | 411 | Q_DECLARE_OPERATORS_FOR_FLAGS(QJsonTreeItem::SpecialFlags) 412 | 413 | #endif // QJSONTREEITEM_H 414 | -------------------------------------------------------------------------------- /libs/qjsontreewidget/qjsontreeitemdelegate.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of QJsonTreeWidget. 3 | 4 | Copyright (C) 2012 valerino 5 | 6 | QJsonTreeWidget is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | QJsonTreeWidget is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with QJsonTreeWidget. If not, see . 18 | */ 19 | 20 | #include "qjsontreeitemdelegate.h" 21 | #include "qjsontreewidget.h" 22 | 23 | QJsonTreeItemDelegate::QJsonTreeItemDelegate(QObject *parent) : 24 | QStyledItemDelegate(parent) 25 | { 26 | // initialize hash used to speedup paint() function 27 | buildWidgetTypes(); 28 | } 29 | 30 | QJsonTreeItemDelegate::~QJsonTreeItemDelegate() 31 | { 32 | } 33 | 34 | QWidget *QJsonTreeItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const 35 | { 36 | Q_UNUSED(option); 37 | 38 | QModelIndex idx = QJsonSortFilterProxyModel::indexToSourceIndex(index); 39 | const QJsonTreeModel* model = static_cast(idx.model()); 40 | 41 | // get tag for this index 42 | QJsonTreeItem* item; 43 | QString tag = model->tagByModelIndex(idx,&item); 44 | if (tag.isEmpty()) 45 | return 0; 46 | 47 | // check if editing is enabled on the widget 48 | if (!item->widget()->editingEnabled()) 49 | return 0; 50 | 51 | // get widget string 52 | QString w = item->map().value("_widget_:" % tag,QString()).toString(); 53 | if (w.isEmpty()) 54 | return 0; 55 | 56 | // get value and create the widget 57 | if (w.compare("QCheckBox",Qt::CaseInsensitive) == 0) 58 | { 59 | // create a checkbox 60 | QCheckBox* w = new QCheckBox(parent); 61 | return w; 62 | } 63 | else if (w.compare("QSpinBox",Qt::CaseInsensitive) == 0) 64 | { 65 | // create a spinbox 66 | QSpinBox* w = new QSpinBox(parent); 67 | w->setMinimum(item->map().value("_valuemin_:" % tag,0).toInt()); 68 | w->setMaximum(item->map().value("_valuemax_:" % tag,0).toInt()); 69 | return w; 70 | } 71 | else if (w.compare("QComboBox",Qt::CaseInsensitive) == 0) 72 | { 73 | // create a combobox 74 | QComboBox* w = new QComboBox(parent); 75 | QString ls = item->map().value("_valuelist_:" % tag,QStringList()).toString(); 76 | if (!ls.isEmpty()) 77 | { 78 | // set values 79 | QStringList l = ls.split(","); 80 | if (!l.isEmpty()) 81 | w->addItems(l); 82 | } 83 | return w; 84 | } 85 | else if (w.compare("QLineEdit",Qt::CaseInsensitive) == 0) 86 | { 87 | // create a lineedit 88 | QLineEdit* w = new QLineEdit(parent); 89 | 90 | // check if we have a regexp set 91 | QString re = item->map().value("_regexp_:" % tag,QString()).toString(); 92 | if (!re.isEmpty()) 93 | { 94 | // set a validator 95 | QRegExp rx(re); 96 | QRegExpValidator* v = new QRegExpValidator(rx,w); 97 | w->setValidator(v); 98 | } 99 | return w; 100 | } 101 | return 0; 102 | } 103 | 104 | void QJsonTreeItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const 105 | { 106 | QModelIndex idx = QJsonSortFilterProxyModel::indexToSourceIndex(index); 107 | QVariant val = idx.model()->data(idx,Qt::DisplayRole); 108 | QString n (editor->metaObject()->className()); 109 | 110 | if (n.compare("QCheckBox",Qt::CaseInsensitive) == 0) 111 | { 112 | QCheckBox* w = static_cast(editor); 113 | w->setChecked(val.toBool()); 114 | } 115 | else if (n.compare("QSpinBox",Qt::CaseInsensitive) == 0) 116 | { 117 | QSpinBox* w = static_cast(editor); 118 | w->setValue(val.toInt()); 119 | } 120 | else if (n.compare("QComboBox",Qt::CaseInsensitive) == 0) 121 | { 122 | QComboBox* w = static_cast(editor); 123 | int i = w->findText(val.toString(),Qt::MatchExactly); 124 | if (i != -1) 125 | w->setCurrentIndex(i); 126 | } 127 | else if (n.compare("QLineEdit",Qt::CaseInsensitive) == 0) 128 | { 129 | QLineEdit* w = static_cast(editor); 130 | w->setText(val.toString()); 131 | } 132 | } 133 | 134 | void QJsonTreeItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const 135 | { 136 | // we use the proxy model index here, since we set data 137 | QString n (editor->metaObject()->className()); 138 | 139 | if (n.compare("QCheckBox",Qt::CaseInsensitive) == 0) 140 | { 141 | QCheckBox* w = static_cast(editor); 142 | model->setData(index,w->isChecked(),Qt::EditRole); 143 | } 144 | else if (n.compare("QSpinBox",Qt::CaseInsensitive) == 0) 145 | { 146 | QSpinBox* w = static_cast(editor); 147 | model->setData(index,w->value(),Qt::EditRole); 148 | } 149 | else if (n.compare("QComboBox",Qt::CaseInsensitive) == 0) 150 | { 151 | QComboBox* w = static_cast(editor); 152 | model->setData(index,w->currentText(),Qt::EditRole); 153 | } 154 | else if (n.compare("QLineEdit",Qt::CaseInsensitive) == 0) 155 | { 156 | QLineEdit* w = static_cast(editor); 157 | QRegExpValidator* v = (QRegExpValidator*)w->validator(); 158 | if (!v) 159 | { 160 | // no validator 161 | model->setData(index,w->text(),Qt::EditRole); 162 | return; 163 | } 164 | 165 | // discard anything not satisfying the regexp 166 | int pos = 0; 167 | QString t = w->text(); 168 | if (v->validate(t,pos) == QValidator::Acceptable) 169 | model->setData(index,w->text(),Qt::EditRole); 170 | } 171 | } 172 | 173 | void QJsonTreeItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const 174 | { 175 | QModelIndex idx = QJsonSortFilterProxyModel::indexToSourceIndex(index); 176 | const QJsonTreeModel* model = static_cast(idx.model()); 177 | QJsonTreeItem* it; 178 | QVariantMap m = model->mapByModelIndex(idx,&it); 179 | if (m.isEmpty()) 180 | { 181 | QStyledItemDelegate::paint(painter,option,idx); 182 | return; 183 | } 184 | 185 | // get headers hash 186 | QHash h = it->headerHashByIdx(idx.column()); 187 | 188 | // we always paint the checkbox 189 | QString w = m.value("_widget_:" % h["__tag__"].toString(),QString()).toString(); 190 | QStyle::ControlElement ce = m_widgetTypes.value(w,(QStyle::ControlElement)-1); 191 | if (ce == QStyle::CE_CheckBox) 192 | { 193 | // draw a checkbox 194 | drawButton(option,painter,QStyle::CE_CheckBox,QString(),QString(),m.value(h["__tag__"].toString(),false).toBool()); 195 | return; 196 | } 197 | 198 | // check if we need to paint something in this column 199 | if (!h["__draw__"].toBool()) 200 | { 201 | QStyledItemDelegate::paint(painter,option,idx); 202 | return; 203 | } 204 | 205 | // check if the item has the corresponding tag 206 | QString tagval = m.value(h["__tag__"].toString(),QVariant()).toString(); 207 | if (tagval.isEmpty()) 208 | { 209 | QStyledItemDelegate::paint(painter,option,idx); 210 | return; 211 | } 212 | 213 | // see what we have to draw 214 | // ,, separated string: 0:widget, 1:text, 2:optional pixmap 215 | QStringList l = tagval.split(",,"); 216 | if (l.isEmpty()) 217 | { 218 | QStyledItemDelegate::paint(painter,option,idx); 219 | return; 220 | } 221 | ce = m_widgetTypes.value(l.at(0),(QStyle::ControlElement)-1); 222 | if (ce == QStyle::CE_PushButton) 223 | { 224 | // draw a pushbutton 225 | drawButton(option,painter,QStyle::CE_PushButton,l.count()>=2 ? l.at(1):QString(),l.count()==3 ? l.at(2):QString()); 226 | return; 227 | } 228 | } 229 | 230 | void QJsonTreeItemDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const 231 | { 232 | Q_UNUSED(index); 233 | editor->setGeometry(option.rect); 234 | } 235 | 236 | bool QJsonTreeItemDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) 237 | { 238 | Q_UNUSED(model); 239 | Q_UNUSED(option); 240 | 241 | QMouseEvent* me; 242 | 243 | switch (event->type()) 244 | { 245 | case QEvent::MouseButtonPress: 246 | me = (QMouseEvent*)event; 247 | switch (me->button()) 248 | { 249 | case Qt::LeftButton: 250 | // left button pressed 251 | handleLeftMousePress(index); 252 | break; 253 | case Qt::RightButton: 254 | // right button pressed 255 | handleRightMousePress(me,index); 256 | break; 257 | 258 | default: 259 | break; 260 | } 261 | break; 262 | 263 | default: 264 | break; 265 | } 266 | // we always return false to let the selection model do its work, without eating the event 267 | return false; 268 | } 269 | 270 | void QJsonTreeItemDelegate::drawButton(const QStyleOptionViewItem &option, QPainter* painter, const QStyle::ControlElement type, const QString &text, const QString& pixmap, bool checked) const 271 | { 272 | // copy the options from the provided one 273 | QStyleOptionButton opts; 274 | opts.features = QStyleOptionButton::None; 275 | opts.rect = option.rect; 276 | opts.direction = option.direction; 277 | opts.state = option.state; 278 | checked ? opts.state |= QStyle::State_On : opts.state |= QStyle::State_Off; 279 | if (!pixmap.isEmpty()) 280 | { 281 | opts.icon = QIcon(pixmap); 282 | opts.iconSize = QSize(16,16); 283 | } 284 | if (!text.isEmpty()) 285 | opts.text = text; 286 | QApplication::style()->drawControl(type,&opts,painter); 287 | } 288 | 289 | void QJsonTreeItemDelegate::buildWidgetTypes() 290 | { 291 | m_widgetTypes["QPushButton"] = QStyle::CE_PushButton; 292 | m_widgetTypes["QCheckBox"] = QStyle::CE_CheckBox; 293 | } 294 | 295 | void QJsonTreeItemDelegate::handleLeftMousePress(const QModelIndex &index) 296 | { 297 | QModelIndex idx = QJsonSortFilterProxyModel::indexToSourceIndex(index); 298 | const QJsonTreeModel* model = static_cast(idx.model()); 299 | 300 | // get item 301 | QJsonTreeItem* item; 302 | QVariantMap m = model->mapByModelIndex(idx,&item); 303 | if (m.isEmpty()) 304 | return; 305 | 306 | // check if editing is enabled on the widget 307 | if (!item->widget()->editingEnabled()) 308 | return; 309 | 310 | // get stuff from item 311 | QString tag = item->headerTagByIdx(idx.column()); 312 | QVariant val = m.value(tag,QVariant()); 313 | 314 | // check if there's hide or readonly set for this column 315 | if ((m.value("_readonly_:" % tag, false).toBool() == true) && (model->specialFlags() & QJsonTreeItem::HonorReadOnly)) 316 | return; 317 | 318 | // emit the generic signal 319 | emit clicked(idx.column(),idx.row(),tag,val,item); 320 | 321 | // if it's a button, emit the button clicked signal too. this is just a shortcut for the above signal 322 | if (val.toString().startsWith("QPushButton,",Qt::CaseInsensitive) && !val.isNull()) 323 | { 324 | emit clicked( item,tag); 325 | } 326 | } 327 | 328 | void QJsonTreeItemDelegate::handleRightMousePress(QMouseEvent* event, const QModelIndex &index) 329 | { 330 | QModelIndex idx = QJsonSortFilterProxyModel::indexToSourceIndex(index); 331 | const QJsonTreeModel* model = static_cast(idx.model()); 332 | QJsonTreeItem* item; 333 | QVariantMap m = model->mapByModelIndex(idx,&item); 334 | if (!item) 335 | return; 336 | 337 | // check if editing is enabled 338 | if (!item->widget()->editingEnabled()) 339 | return; 340 | 341 | QString name = m["name"].toString(); 342 | bool canadd = true; 343 | 344 | // get templates this item supports 345 | QList templates = templatesByItem(item); 346 | if (templates.isEmpty()) 347 | { 348 | // check if this item parent has a template for this item 349 | QJsonTreeItem* tp = templateByName(item,name); 350 | if (!tp) 351 | return; 352 | templates.append(tp); 353 | canadd = false; 354 | } 355 | 356 | // create a popup menu 357 | QMenu* menu = new QMenu(); 358 | foreach (QJsonTreeItem* t, templates) 359 | { 360 | // check if this item can be added (coming from item templates) 361 | if (canadd) 362 | { 363 | QAction* action = new QAction(tr("Add '") % t->map()["name"].toString() % "'",menu); 364 | 365 | // swap purgelist if set, replacing after toMap() 366 | QHash purgelist = t->widget()->purgeListOnSave(); 367 | t->widget()->setPurgeListOnSave(QHash()); 368 | action->setData(t->toMap()); 369 | t->widget()->setPurgeListOnSave(purgelist); 370 | menu->addAction(action); 371 | } 372 | else 373 | { 374 | // check if this item is mandatory and cannot be removed 375 | bool enableaction = true; 376 | if (t->map().value("_mandatory_",false).toBool() == true) 377 | { 378 | if (countParentChildsByName(item,name) == 1) 379 | enableaction = false; 380 | } 381 | 382 | // not mandatory, can remove 383 | QAction* action = new QAction(tr("Remove '") % t->map()["name"].toString() % "'",menu); 384 | action->setData(QVariant(true)); 385 | action->setEnabled(enableaction); 386 | menu->addAction(action); 387 | } 388 | } 389 | 390 | // finally exec the menu 391 | execMenu(idx, item, menu, event->globalPos()); 392 | delete menu; 393 | } 394 | 395 | void QJsonTreeItemDelegate::execMenu(const QModelIndex& index, QJsonTreeItem* item, QMenu *menu, const QPoint& pos) const 396 | { 397 | // index is already the converted proxy->source index 398 | QJsonTreeModel* model = const_cast(static_cast(index.model())); 399 | QAction* action = menu->exec(pos); 400 | if (action) 401 | { 402 | QJsonTreeWidget* tree = model->root()->widget(); 403 | tree->setDynamicSortFiltering(false); 404 | if (action->data().canConvert(QVariant::Bool)) // we've set this before 405 | { 406 | // we must remove 407 | model->removeRow(index.row(),index.parent()); 408 | } 409 | else 410 | { 411 | // we must insert, we've stored a map at action->data 412 | QVariantMap mm = action->data().toMap(); 413 | mm.remove("_template_"); 414 | mm.remove("_mandatory_"); 415 | model->insertRow(item->childCount(),index); 416 | QModelIndex newidx = model->index(item->childCount() - 1,0,index); 417 | model->setData(newidx,mm); 418 | } 419 | tree->setDynamicSortFiltering(true); 420 | } 421 | } 422 | 423 | QList QJsonTreeItemDelegate::templatesByItem(QJsonTreeItem* item) const 424 | { 425 | QList l; 426 | foreach (QJsonTreeItem* c, item->children()) 427 | { 428 | if (c->map().value("_template_",false).toBool() == true) 429 | { 430 | l.append(c); 431 | } 432 | } 433 | return l; 434 | } 435 | 436 | QJsonTreeItem* QJsonTreeItemDelegate::templateByName(QJsonTreeItem* item, const QString& name) const 437 | { 438 | // get parent templates 439 | QJsonTreeItem* parent = item->parent(); 440 | if (!parent) 441 | return 0; 442 | 443 | foreach (QJsonTreeItem* c, parent->children()) 444 | { 445 | if (c->map().value("_template_",false).toBool() == true) 446 | { 447 | // get template for this name 448 | if (c->map()["name"].toString().compare(name,Qt::CaseInsensitive) == 0) 449 | return c; 450 | } 451 | } 452 | return 0; 453 | } 454 | 455 | int QJsonTreeItemDelegate::countParentChildsByName(QJsonTreeItem* item, const QString& name) const 456 | { 457 | int count = 0; 458 | 459 | // get parent templates 460 | QJsonTreeItem* parent = item->parent(); 461 | if (!parent) 462 | return count; 463 | 464 | foreach (QJsonTreeItem* c, parent->children()) 465 | { 466 | // do not count templates 467 | if (c->map().value("_template_",false).toBool() == true) 468 | continue; 469 | 470 | // check if it has the same name 471 | if (c->map()["name"].toString().compare(name,Qt::CaseInsensitive) == 0) 472 | count++; 473 | } 474 | return count; 475 | } 476 | -------------------------------------------------------------------------------- /libs/qjsontreewidget/qjsontreeitemdelegate.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of QJsonTreeWidget. 3 | 4 | Copyright (C) 2012 valerino 5 | 6 | QJsonTreeWidget is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | QJsonTreeWidget is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with QJsonTreeWidget. If not, see . 18 | */ 19 | 20 | #ifndef QJSONTREEITEMDELEGATE_H 21 | #define QJSONTREEITEMDELEGATE_H 22 | 23 | #include 24 | #include 25 | #include "qjsontreemodel.h" 26 | #include "qjsonsortfilterproxymodel.h" 27 | 28 | class QJsonTreeWidget; 29 | 30 | /** 31 | * @brief class to display/edit data using the QJsonTreeModel model class 32 | * 33 | */ 34 | class QJsonTreeItemDelegate : public QStyledItemDelegate 35 | { 36 | friend class QJsonTreeModel; 37 | friend class QJsonTreeItem; 38 | 39 | Q_OBJECT 40 | public: 41 | /** 42 | * @brief constructor 43 | * 44 | * @param proxy the proxy model used for sorting/filtering 45 | */ 46 | explicit QJsonTreeItemDelegate(QObject *parent = 0); 47 | 48 | /** 49 | * @brief destructor 50 | * 51 | */ 52 | virtual ~QJsonTreeItemDelegate(); 53 | 54 | /** 55 | * @brief reimplementation of createEditor() from QAbstractItemDelegate interface 56 | * 57 | * @param parent the parent widget 58 | * @param option parameters to draw the widget 59 | * @param index the model index 60 | */ 61 | virtual QWidget* createEditor ( QWidget * parent, const QStyleOptionViewItem & option, const QModelIndex & index ) const; 62 | 63 | /** 64 | * @brief reimplementation of setEditorData() from QAbstractItemDelegate interface 65 | * 66 | * @param editor the editor 67 | * @param index the model index 68 | */ 69 | virtual void setEditorData ( QWidget * editor, const QModelIndex & index ) const; 70 | 71 | /** 72 | * @brief reimplementation of setModelData() from QAbstractItemDelegate interface 73 | * 74 | * @param editor the editor 75 | * @param model the model 76 | * @param index the model index 77 | */ 78 | virtual void setModelData ( QWidget * editor, QAbstractItemModel * model, const QModelIndex & index ) const; 79 | 80 | /** 81 | * @brief reimplementation of paint() from QAbstractItemDelegate interface 82 | * 83 | * @param painter the painter to render the item 84 | * @param option the options to render the item 85 | * @param index the model index 86 | */ 87 | virtual void paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const; 88 | 89 | /** 90 | * @brief reimplementation of updateEditorGeometry() from QAbstractItemDelegate interface 91 | * 92 | * @param editor the editor 93 | * @param option the options to render the item 94 | * @param index the model index 95 | */ 96 | virtual void updateEditorGeometry ( QWidget * editor, const QStyleOptionViewItem & option, const QModelIndex & index ) const; 97 | 98 | /** 99 | * @brief reimplementation of editorEvent() from QAbstractItemDelegate interface 100 | * 101 | * @param event the event (mouse events, ...) 102 | * @param model the model 103 | * @param option the options to render the item 104 | * @param index the model index 105 | */ 106 | virtual bool editorEvent ( QEvent * event, QAbstractItemModel * model, const QStyleOptionViewItem & option, const QModelIndex & index ); 107 | 108 | signals: 109 | void clicked (int column, int row, const QString& jsontag, const QVariant& value, const QJsonTreeItem* item); 110 | void clicked (const QJsonTreeItem* item, const QString& jsontag); 111 | 112 | private: 113 | QList templatesByItem(QJsonTreeItem *item) const; 114 | QJsonTreeItem* templateByName(QJsonTreeItem *item, const QString &name) const; 115 | int countParentChildsByName(QJsonTreeItem *item, const QString &name) const; 116 | void handleLeftMousePress(const QModelIndex &index); 117 | void handleRightMousePress(QMouseEvent *event, const QModelIndex &index); 118 | void drawButton(const QStyleOptionViewItem &option, QPainter *painter, const QStyle::ControlElement type, const QString &text=QString(), const QString& pixmap=QString(), bool checked=false) const; 119 | QHash m_widgetTypes; 120 | void buildWidgetTypes(); 121 | void execMenu(const QModelIndex &index, QJsonTreeItem *item, QMenu *menu, const QPoint &pos) const; 122 | }; 123 | 124 | #endif // QJSONTREEITEMDELEGATE_H 125 | -------------------------------------------------------------------------------- /libs/qjsontreewidget/qjsontreemodel.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of QJsonTreeWidget. 3 | 4 | Copyright (C) 2012 valerino 5 | 6 | QJsonTreeWidget is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | QJsonTreeWidget is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with QJsonTreeWidget. If not, see . 18 | */ 19 | 20 | #include "qjsontreemodel.h" 21 | 22 | QJsonTreeModel::QJsonTreeModel(QObject *parent, QJsonTreeItem* root) : 23 | QAbstractItemModel(parent) 24 | { 25 | m_specialFlags = QJsonTreeItem::HonorAll; 26 | m_childsFont = QFont(); 27 | m_childsFontValid = false; 28 | m_childsForeColor = QColor(); 29 | m_childsBackColor = QColor(); 30 | m_parentsFont = QFont(); 31 | m_parentsFontValid = false; 32 | m_parentsForeColor = QColor(); 33 | m_parentsBackColor = QColor(); 34 | 35 | m_root = root; 36 | } 37 | 38 | QJsonTreeModel::~QJsonTreeModel() 39 | { 40 | this->clear(); 41 | } 42 | 43 | 44 | QJsonTreeItem *QJsonTreeModel::parentItem(const QModelIndex &parent) const 45 | { 46 | if (!parent.isValid()) 47 | { 48 | // invalid, use root item 49 | return m_root; 50 | } 51 | // get from index 52 | return static_cast(parent.internalPointer()); 53 | } 54 | 55 | QModelIndex QJsonTreeModel::index(int row, int column, const QModelIndex &parent) const 56 | { 57 | // if we haven't an index, just return an empty index 58 | if (!hasIndex(row, column, parent)) 59 | return QModelIndex(); 60 | 61 | // get the parent item 62 | QJsonTreeItem* parentit = parentItem(parent); 63 | if (parentit == 0) 64 | return QModelIndex(); 65 | 66 | // since we're referring to a child item of the parent, if it exists create an index for it 67 | QJsonTreeItem* child = parentit->child(row); 68 | if (!child) 69 | return QModelIndex(); 70 | 71 | // check various item options 72 | QVariantMap m = child->map(); 73 | QString tag = child->headerTagByIdx(column); 74 | bool b = m.value("__hasROSet__",false).toBool(); 75 | if (b && (m_specialFlags & QJsonTreeItem::ReadOnlyHidesRow) && (m_specialFlags & QJsonTreeItem::HonorHide)) 76 | { 77 | // hides the whole row 78 | return QModelIndex(); 79 | } 80 | 81 | b = m.value("_template_",false).toBool(); 82 | if (b) 83 | { 84 | // always hide templates 85 | return QModelIndex(); 86 | } 87 | 88 | b = m.value("_hide_",false).toBool(); 89 | if (b && (m_specialFlags & QJsonTreeItem::HonorHide)) 90 | { 91 | // hide the whole row 92 | return QModelIndex(); 93 | } 94 | b = m.value("_hide_:" % tag,false).toBool(); 95 | if (b && (m_specialFlags & QJsonTreeItem::HonorHide)) 96 | { 97 | // hide only this value 98 | return QModelIndex(); 99 | } 100 | return createIndex (row, column, child); 101 | } 102 | 103 | QModelIndex QJsonTreeModel::parent(const QModelIndex &index) const 104 | { 105 | if (!index.isValid()) 106 | return QModelIndex(); 107 | 108 | // look for child parent 109 | QJsonTreeItem* child = static_cast(index.internalPointer()); 110 | if (child == 0) 111 | return QModelIndex(); 112 | 113 | QJsonTreeItem* parent = child->parent(); 114 | 115 | if (parent == m_root) 116 | return QModelIndex(); 117 | 118 | return createIndex (parent->row(), 0, parent); 119 | } 120 | 121 | int QJsonTreeModel::columnCount(const QModelIndex &parent) const 122 | { 123 | Q_UNUSED(parent); 124 | if (m_root) 125 | { 126 | // return root item's column count (from the _columns_ descriptor) 127 | return m_root->columnCount(); 128 | } 129 | return 0; 130 | } 131 | 132 | QVariant QJsonTreeModel::data(const QModelIndex &index, int role) const 133 | { 134 | QJsonTreeItem* item; 135 | QString tag = tagByModelIndex(index,&item,role); 136 | if (tag.isEmpty()) 137 | return QVariant(); 138 | 139 | // check roles 140 | switch (role) 141 | { 142 | case Qt::ForegroundRole: 143 | // read only should be always displayed as disabled 144 | if (item->map().contains("_readonly_:" % tag)) 145 | return QVariant(); 146 | 147 | // item color has precedence 148 | if (item->foregroundColor().isValid() && (m_specialFlags & QJsonTreeItem::HonorItemForegroundColor)) 149 | return QVariant(item->foregroundColor()); 150 | 151 | // check parent/child color then 152 | if (item->isTree() || item->hasChildren()) 153 | { 154 | if (m_parentsForeColor.isValid() && (m_specialFlags & QJsonTreeItem::HonorParentsForegroundColor)) 155 | return QVariant(m_parentsForeColor); 156 | } 157 | else 158 | { 159 | if (m_childsForeColor.isValid() && (m_specialFlags & QJsonTreeItem::HonorChildsForegroundColor)) 160 | return QVariant(m_childsForeColor); 161 | } 162 | 163 | // then the column color 164 | if (columnForegroundColor(tag).isValid() && (m_specialFlags & QJsonTreeItem::HonorColumnForegroundColor)) 165 | return QVariant(columnForegroundColor(tag)); 166 | return QVariant(); 167 | break; 168 | 169 | case Qt::BackgroundRole: 170 | // item color has precedence 171 | if (item->backgroundColor().isValid() && (m_specialFlags & QJsonTreeItem::HonorItemBackgroundColor)) 172 | return QVariant(item->backgroundColor()); 173 | 174 | // check parent/child color then 175 | if (item->isTree() || item->hasChildren()) 176 | { 177 | if (m_parentsBackColor.isValid() && (m_specialFlags & QJsonTreeItem::HonorParentsBackgroundColor)) 178 | return QVariant(m_parentsBackColor); 179 | } 180 | else 181 | { 182 | if (m_childsBackColor.isValid() && (m_specialFlags & QJsonTreeItem::HonorChildsBackgroundColor)) 183 | return QVariant(m_childsBackColor); 184 | } 185 | 186 | // then the column color 187 | if (columnBackgroundColor(tag).isValid() && (m_specialFlags & QJsonTreeItem::HonorColumnBackgroundColor)) 188 | return QVariant(columnBackgroundColor(tag)); 189 | return QVariant(); 190 | break; 191 | 192 | case Qt::FontRole: 193 | // item font has precedence 194 | if (item->isFontValid() && (m_specialFlags & QJsonTreeItem::HonorItemFont)) 195 | return QVariant(item->font()); 196 | 197 | // check parent/child font then 198 | if (item->isTree() || item->hasChildren()) 199 | { 200 | if (m_parentsFontValid && (m_specialFlags & QJsonTreeItem::HonorParentsFont)) 201 | return QVariant(m_parentsFont); 202 | } 203 | else 204 | { 205 | if (m_childsFontValid && (m_specialFlags & QJsonTreeItem::HonorChildsFont)) 206 | return QVariant(m_childsFont); 207 | } 208 | 209 | // then the column font 210 | if (!(m_specialFlags & QJsonTreeItem::HonorColumnFont)) 211 | return QVariant(); 212 | if (m_columnFonts.value(tag % ":valid",false).toBool()) 213 | return QVariant(columnFont(tag)); 214 | return QVariant(); 215 | break; 216 | 217 | default: 218 | break; 219 | } 220 | 221 | // skip custom drawn items (they could be buttons, they have usually no values... maybe we could change that later) 222 | QHash > h = item->headers(); 223 | if (h[tag].contains("__draw__")) 224 | return QVariant(); 225 | 226 | // get the value that has been set in json 227 | return item->map().value(tag,QVariant()); 228 | } 229 | 230 | bool QJsonTreeModel::setData(const QModelIndex &index, const QVariant &value, int role) 231 | { 232 | QJsonTreeItem* item = itemByModelIndex(index,role); 233 | if (!item) 234 | return false; 235 | if (value.canConvert(QVariant::Map)) 236 | { 237 | // replace the whole map 238 | item->fromMap(value.toMap(),item->parent()); 239 | } 240 | else 241 | { 242 | // replace data at the specified JSON tag 243 | item->setMapValue(index.column(),value); 244 | } 245 | emit dataChanged(index,index); 246 | 247 | return true; 248 | } 249 | 250 | Qt::ItemFlags QJsonTreeModel::flags(const QModelIndex &index) const 251 | { 252 | // default 253 | Qt::ItemFlags f = QAbstractItemModel::flags(index); 254 | 255 | // get tag for this index 256 | QJsonTreeItem* item; 257 | QString tag = tagByModelIndex(index,&item); 258 | if (tag.isEmpty()) 259 | return f; 260 | 261 | // if it's readonly, remove the enabled flag 262 | bool b = item->map().value("_readonly_:" % tag,false).toBool(); 263 | if (b && (m_specialFlags & QJsonTreeItem::HonorReadOnly)) 264 | { 265 | f &= ~Qt::ItemIsEnabled; 266 | } 267 | 268 | // if it's a widget, get flags to apply from the Qt::ItemFlags stored in our hash 269 | QString w = item->map().value("_widget_:" % tag,QString()).toString(); 270 | if (!w.isEmpty()) 271 | { 272 | f |= (QJsonTreeItem::widgetFlags[w]); 273 | } 274 | return f; 275 | } 276 | 277 | QVariant QJsonTreeModel::headerData(int section, Qt::Orientation orientation, int role) const 278 | { 279 | Q_UNUSED(orientation); 280 | if (!m_root) 281 | return QVariant(); 282 | 283 | if (role == Qt::DisplayRole) 284 | return m_root->headerNameByIdx(section); 285 | return QVariant(); 286 | } 287 | 288 | bool QJsonTreeModel::removeRows(int row, int count, const QModelIndex &parent) 289 | { 290 | QJsonTreeItem* parentit = itemByModelIndex(parent); 291 | if (!parentit || count == 0) 292 | return false; 293 | 294 | // this will remove rows starting from the specified row 295 | beginRemoveRows(parent,row,row+count-1); 296 | for (int i=row; i < (row+count); i++) 297 | { 298 | // this deletes the child too 299 | parentit->removeChild(i); 300 | } 301 | endRemoveRows(); 302 | return true; 303 | } 304 | 305 | bool QJsonTreeModel::insertRows(int row, int count, const QModelIndex &parent) 306 | { 307 | QJsonTreeItem* parentit = itemByModelIndex(parent); 308 | if (!parentit || count == 0) 309 | return false; 310 | 311 | beginInsertRows(parent,row,row+count-1); 312 | for (int i = 0; i < count; i++) 313 | { 314 | QJsonTreeItem* newitem = new QJsonTreeItem(parentit->widget(),parentit); 315 | parentit->appendChild(newitem); 316 | } 317 | endInsertRows(); 318 | 319 | return true; 320 | } 321 | 322 | bool QJsonTreeModel::insertRow(int row, const QModelIndex &parent) 323 | { 324 | return insertRows(row,1,parent); 325 | } 326 | 327 | bool QJsonTreeModel::hasChildren(const QModelIndex &parent) 328 | { 329 | QJsonTreeItem* item = itemByModelIndex(parent); 330 | if (item && item->childCount() > 0) 331 | return true; 332 | return false; 333 | } 334 | 335 | int QJsonTreeModel::rowCount(const QModelIndex &parent) const 336 | { 337 | // since it's a tree, consider column 0 only 338 | if (parent.column() > 0) 339 | return 0; 340 | 341 | QJsonTreeItem* item = parentItem(parent); 342 | if (item == 0) 343 | return 0; 344 | 345 | // simply return item children count (= rows under that item) 346 | return item->childCount(); 347 | } 348 | 349 | void QJsonTreeModel::clear() 350 | { 351 | beginResetModel(); 352 | if (m_root) 353 | { 354 | delete m_root; 355 | m_root = 0; 356 | } 357 | endResetModel(); 358 | } 359 | 360 | void QJsonTreeModel::setSpecialFlags(QJsonTreeItem::SpecialFlags flags) 361 | { 362 | // special flags is updated, so we need to change the layout and inform the view 363 | emit layoutAboutToBeChanged(); 364 | m_specialFlags = flags; 365 | emit layoutChanged(); 366 | } 367 | 368 | QJsonTreeItem *QJsonTreeModel::itemByModelIndex(const QModelIndex &index, int role) const 369 | { 370 | // check if index is valid and one of these roles is requested 371 | QList roles; 372 | roles << Qt::DisplayRole << Qt::EditRole << Qt::FontRole << Qt::BackgroundRole << Qt::ForegroundRole << Qt::ToolTipRole; 373 | if (!index.isValid() || !roles.contains(role)) 374 | return 0; 375 | 376 | // get item 377 | return static_cast(index.internalPointer()); 378 | } 379 | 380 | QVariantMap QJsonTreeModel::mapByModelIndex(const QModelIndex &index, QJsonTreeItem** item, int role) const 381 | { 382 | QJsonTreeItem* it = itemByModelIndex(index,role); 383 | if (!it) 384 | return QVariantMap(); 385 | 386 | if (item) 387 | *item = it; 388 | 389 | // get item map 390 | return it->map(); 391 | } 392 | 393 | const QString QJsonTreeModel::tagByModelIndex (const QModelIndex &index, QJsonTreeItem** item, int role) const 394 | { 395 | // get item data 396 | QJsonTreeItem* it; 397 | QVariantMap m = mapByModelIndex(index,&it,role); 398 | if (m.isEmpty()) 399 | return QString(); 400 | if (item) 401 | *item = it; 402 | return it->headerTagByIdx(index.column()); 403 | } 404 | 405 | const QModelIndex QJsonTreeModel::indexByItem(QJsonTreeItem* item, int column) const 406 | { 407 | if (item == m_root) 408 | return QModelIndex(); 409 | QJsonTreeItem* par = item->parent(); 410 | if (!par) 411 | par = m_root; 412 | int row = par->children().lastIndexOf(item); 413 | return createIndex (row,column,item); 414 | } 415 | -------------------------------------------------------------------------------- /libs/qjsontreewidget/qjsontreemodel.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of QJsonTreeWidget. 3 | 4 | Copyright (C) 2012 valerino 5 | 6 | QJsonTreeWidget is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | QJsonTreeWidget is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with QJsonTreeWidget. If not, see . 18 | */ 19 | 20 | #ifndef QJSONTREEMODEL_H 21 | #define QJSONTREEMODEL_H 22 | 23 | #include 24 | #include "qjsontreeitem.h" 25 | #include 26 | class QJsonTreeItemDelegate; 27 | 28 | /** 29 | * @brief class to model a tree from a JSON file/buffer coming from QJson 30 | * 31 | */ 32 | class QJsonTreeModel : public QAbstractItemModel 33 | { 34 | friend class QJsonTreeItem; 35 | friend class QJsonTreeWidget; 36 | friend class QJsonTreeItemDelegate; 37 | friend class QJsonSortFilterProxyModel; 38 | 39 | Q_OBJECT 40 | public: 41 | /** 42 | * @brief constructor 43 | * 44 | * @param parent the parent object (optional) 45 | * @param root the root item (optional) 46 | */ 47 | explicit QJsonTreeModel(QObject *parent = 0, QJsonTreeItem* root=0); 48 | 49 | /** 50 | * @brief destructor 51 | * 52 | */ 53 | virtual ~QJsonTreeModel(); 54 | 55 | /** 56 | * @brief sets the root item, invalidating the model (calls clear()) 57 | * 58 | * @param root the root item 59 | */ 60 | void setRoot(QJsonTreeItem* root) { this->clear(); m_root = root;} 61 | 62 | /** 63 | * @brief returns the root tree item (the whole tree itself), which is used only to store private data. 64 | * All the displayed items by the view are childs of this item. 65 | * 66 | * @return QJsonTreeItem 67 | */ 68 | QJsonTreeItem* root() const { return m_root; } 69 | 70 | /** 71 | * @brief reimplementation of index() from the QAbstractItemModel interface 72 | * 73 | * @param row the row 74 | * @param column the column 75 | * @param parent the parent index (optional) 76 | * @return QModelIndex 77 | */ 78 | virtual QModelIndex index ( int row, int column, const QModelIndex & parent = QModelIndex()) const; 79 | 80 | /** 81 | * @brief reimplementation of parent() from the QAbstractItemModel interface 82 | * 83 | * @param index the model index 84 | * @return QModelIndex 85 | */ 86 | virtual QModelIndex parent ( const QModelIndex & index ) const; 87 | 88 | /** 89 | * @brief reimplementation of rowCount() from the QAbstractItemModel interface 90 | * 91 | * @param parent the parent index (optional) 92 | * @return int 93 | */ 94 | virtual int rowCount ( const QModelIndex & parent = QModelIndex() ) const; 95 | 96 | /** 97 | * @brief reimplementation of columnCount() from the QAbstractItemModel interface 98 | * 99 | * @param parent the parent index (optional) 100 | * @return int 101 | */ 102 | virtual int columnCount ( const QModelIndex & parent = QModelIndex() ) const; 103 | 104 | /** 105 | * @brief reimplementation of data() from the QAbstractItemModel interface 106 | * 107 | * @param index the model index 108 | * @param role the index role (optional) 109 | * @return QVariant 110 | */ 111 | virtual QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const; 112 | 113 | /** 114 | * @brief reimplementation of setData() from the QAbstractItemModel interface, to provide data editing 115 | * 116 | * @param index the model index 117 | * @param value the value to set in the model at index 118 | * @param role the index role (optional) 119 | * @return bool 120 | */ 121 | virtual bool setData ( const QModelIndex & index, const QVariant & value, int role = Qt::EditRole ); 122 | 123 | /** 124 | * @brief reimplementation of flags() from the QAbstractItemModel interface, to provide data editing 125 | * 126 | * @param index the model index 127 | * @return Qt::ItemFlags 128 | */ 129 | virtual Qt::ItemFlags flags ( const QModelIndex & index ) const; 130 | 131 | /** 132 | * @brief reimplementation of headerData() from the QAbstractItemModel interface, to display the column's header. 133 | * 134 | * @param section the header section (= column) 135 | * @param orientation the orientation 136 | * @param role the section role (optional) 137 | * @return QVariant 138 | */ 139 | virtual QVariant headerData ( int section, Qt::Orientation orientation, int role = Qt::DisplayRole ) const; 140 | 141 | /** 142 | * @brief reimplementation of removeRows() from the QAbstractItemModel interface 143 | * 144 | * @param row the (initial) row to remove 145 | * @param count is > 1, remove count rows from row on 146 | * @param parent the parent index (optional) 147 | * @return bool 148 | */ 149 | virtual bool removeRows ( int row, int count, const QModelIndex & parent = QModelIndex()); 150 | 151 | /** 152 | * @brief reimplementation of removeRow() from the QAbstractItemModel interface (this just calls removeRows with count = 1) 153 | * 154 | * @param row the row to remove 155 | * @param parent the parent index (optional) 156 | * @return bool 157 | */ 158 | bool removeRow(int row, const QModelIndex &parent = QModelIndex()) { return removeRows(row,1,parent); } 159 | 160 | /** 161 | * @brief reimplementation of insertRows() from the QAbstractItemModel interface 162 | * 163 | * @param row the row where to append the rows after 164 | * @param count number of rows to insert 165 | * @param parent the parent index (optional) 166 | * @return bool 167 | */ 168 | virtual bool insertRows ( int row, int count, const QModelIndex & parent = QModelIndex()); 169 | 170 | /** 171 | * @brief reimplementation of insertRow() from the QAbstractItemModel interface 172 | * 173 | * @param row the row where to insert the rows after 174 | * @param parent the parent index (optional) 175 | * @return bool 176 | */ 177 | bool insertRow (int row, const QModelIndex &parent = QModelIndex()); 178 | 179 | /** 180 | * @brief reimplementation of hasChildren() from the QAbstractItemModel interface 181 | * 182 | * @param parent the parent index (optional) 183 | * @return bool 184 | */ 185 | virtual bool hasChildren ( const QModelIndex & parent = QModelIndex() ); 186 | 187 | /** 188 | * @brief clears the model by calling reset and deleting the tree 189 | * 190 | */ 191 | void clear(); 192 | 193 | /** 194 | * @brief returns the tree item corresponding to the model index 195 | * 196 | * @param index the model index 197 | * @param role the display role (optional) 198 | * @return QJsonTreeItem 199 | */ 200 | QJsonTreeItem* itemByModelIndex (const QModelIndex& index, int role = Qt::DisplayRole) const; 201 | 202 | /** 203 | * @brief returns the JSON tag corresponding to the model index 204 | * 205 | * @param index the model index 206 | * @param item on return, the corresponding QJsonTreeItem* (optional) 207 | * @param role the display role (optional) 208 | * @return const QString 209 | */ 210 | const QString tagByModelIndex (const QModelIndex &index, QJsonTreeItem** item=0,int role = Qt::DisplayRole) const; 211 | 212 | /** 213 | * @brief returns the map corresponding to the item at model index 214 | * 215 | * @param index the model index 216 | * @param item on return, the corresponding QJsonTreeItem* (optional) 217 | * @param role the display role (optional) 218 | * @return QVariantMap 219 | */ 220 | QVariantMap mapByModelIndex (const QModelIndex& index, QJsonTreeItem** item=0,int role = Qt::DisplayRole) const; 221 | 222 | /** 223 | * @brief returns the modelindex corresponding to a tree item 224 | * 225 | * @param item the QJsonTreeWidget item 226 | * @param column the column 227 | * @return const QModelIndex 228 | */ 229 | const QModelIndex indexByItem(QJsonTreeItem *item, int column) const; 230 | 231 | protected: 232 | void setSpecialFlags(QJsonTreeItem::SpecialFlags flags); 233 | QJsonTreeItem::SpecialFlags specialFlags() const { return m_specialFlags; } 234 | 235 | private: 236 | void setColumnBackgroundColor (const QString& tag, const QColor& color) { m_columnBackColors[tag] = color; } 237 | QColor columnBackgroundColor (const QString& tag) const { return m_columnBackColors.value(tag,QColor()); } 238 | void setColumnForegroundColor (const QString& tag, const QColor& color) { m_columnForeColors[tag] = color; } 239 | QColor columnForegroundColor (const QString& tag) const { return m_columnForeColors.value(tag,QColor()); } 240 | void setColumnFont (const QString& tag, const QFont& font) { m_columnFonts[tag] = font.toString(); m_columnFonts[tag % ":valid"]=true;} 241 | QFont columnFont (const QString& tag) const { QFont f = QFont(); f.fromString(m_columnFonts.value(tag,QString()).toString()); return f; } 242 | 243 | void setParentsBackgroundColor (const QColor& color) {m_parentsBackColor = color;} 244 | QColor parentsBackgroundColor () const { return m_parentsBackColor; } 245 | void setParentsForegroundColor (const QColor& color) {m_parentsForeColor = color;} 246 | QColor parentsForegroundColor () const { return m_parentsForeColor; } 247 | void setParentsFont (const QFont& font) { m_parentsFont = font; m_parentsFontValid = true;} 248 | QFont parentsFont () const { return m_parentsFont; } 249 | 250 | void setChildsBackgroundColor (const QColor& color) {m_childsBackColor = color;} 251 | QColor childsBackgroundColor () const { return m_childsBackColor; } 252 | void setChildsForegroundColor (const QColor& color) {m_childsForeColor = color;} 253 | QColor childsForegroundColor () const { return m_childsForeColor; } 254 | void setChildsFont (const QFont& font) { m_childsFont = font; m_childsFontValid = true;} 255 | QFont childsFont () const { return m_childsFont; } 256 | 257 | QJsonTreeItem* parentItem(const QModelIndex& parent) const; 258 | 259 | QJsonTreeItem* m_root; 260 | QHash m_columnBackColors; 261 | QHash m_columnForeColors; 262 | QVariantMap m_columnFonts; 263 | QColor m_parentsForeColor; 264 | QColor m_parentsBackColor; 265 | QFont m_parentsFont; 266 | bool m_parentsFontValid; 267 | QColor m_childsBackColor; 268 | QColor m_childsForeColor; 269 | QFont m_childsFont; 270 | bool m_childsFontValid; 271 | QJsonTreeItem::SpecialFlags m_specialFlags; 272 | }; 273 | 274 | #endif // QJSONTREEMODEL_H 275 | -------------------------------------------------------------------------------- /libs/qjsontreewidget/qjsontreewidget.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of QJsonTreeWidget. 3 | 4 | Copyright (C) 2012 valerino 5 | 6 | QJsonTreeWidget is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | QJsonTreeWidget is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with QJsonTreeWidget. If not, see . 18 | */ 19 | 20 | #include "qjsontreewidget.h" 21 | 22 | QJsonTreeWidget::QJsonTreeWidget(QWidget *parent, Qt::WindowFlags f) : 23 | QWidget(parent,f) 24 | { 25 | m_maxVersion = JSON_TREE_MAX_VERSION; 26 | m_currentSelection = QModelIndex(); 27 | m_editing = true; 28 | m_purgeDescriptiveTags = false; 29 | m_root = 0; 30 | 31 | // create qjson objects 32 | m_parser = new QJson::Parser(); 33 | m_serializer = new QJson::Serializer(); 34 | m_serializer->setIndentMode(QJson::IndentNone); 35 | 36 | // create the view and organize this widget in a vertical layout 37 | QBoxLayout* l= new QVBoxLayout(this); 38 | m_view = new QTreeView(this); 39 | m_view->setHeaderHidden(false); 40 | m_view->setSortingEnabled(false); 41 | l->addWidget(m_view); 42 | 43 | // add an optional layout for the user to put its controls in 44 | m_optLayout = new QGridLayout(this); 45 | l->addLayout(m_optLayout); 46 | 47 | // set the delegate on the view 48 | m_delegate = new QJsonTreeItemDelegate(this); 49 | m_view->setItemDelegate(m_delegate); 50 | 51 | // add actions reachable by rightclicking on header 52 | m_view->setSelectionBehavior(QAbstractItemView::SelectItems); 53 | m_actionEnableSort = new QAction(tr("Enable sorting"),m_view); 54 | m_actionDisableSort = new QAction(tr("Disable sorting"),m_view); 55 | m_actionLoad = new QAction(tr("Load from JSON file"),m_view); 56 | m_actionSave = new QAction(tr("Save to JSON file"),m_view); 57 | m_actionSaveHtml = new QAction(tr("Save to HTML file"),m_view); 58 | m_actionEnableSort->setData("sortenable"); 59 | m_actionDisableSort->setData("sortdisable"); 60 | m_actionLoad->setData("load"); 61 | m_actionSave->setData("save"); 62 | m_actionSaveHtml->setData("savehtml"); 63 | connect (m_actionLoad,SIGNAL(triggered()),this,SLOT(onActionLoad())); 64 | connect (m_actionSave,SIGNAL(triggered()),this,SLOT(onActionSave())); 65 | connect (m_actionSaveHtml,SIGNAL(triggered()),this,SLOT(onActionSaveHtml())); 66 | connect (m_actionEnableSort,SIGNAL(triggered()),this,SLOT(onActionEnableSort())); 67 | connect (m_actionDisableSort,SIGNAL(triggered()),this,SLOT(onActionDisableSort())); 68 | m_actionLoad->setVisible(false); 69 | m_actionDisableSort->setVisible(false); 70 | m_view->header()->addActions(QList() << m_actionEnableSort << m_actionDisableSort << m_actionLoad << m_actionSave << m_actionSaveHtml); 71 | m_view->header()->setContextMenuPolicy(Qt::ActionsContextMenu); 72 | 73 | // for mouseclicks 74 | connect (m_delegate,SIGNAL(clicked(const QJsonTreeItem*,QString)),this,SIGNAL(clicked(const QJsonTreeItem*,QString))); 75 | connect (m_delegate,SIGNAL(clicked(int,int,QString,QVariant,const QJsonTreeItem*)),this,SIGNAL(clicked(int,int,QString,QVariant,const QJsonTreeItem*))); 76 | 77 | // various options 78 | this->setContextMenuPolicy(Qt::CustomContextMenu); 79 | 80 | // create the model and proxy 81 | m_model = new QJsonTreeModel(this); 82 | connect (m_model,SIGNAL(dataChanged(QModelIndex,QModelIndex)),this,SLOT(onDataChanged(QModelIndex,QModelIndex))); 83 | m_proxyModel = new QJsonSortFilterProxyModel(this); 84 | m_proxyModel->setDynamicSortFilter(true); 85 | m_view->setModel(m_proxyModel); 86 | } 87 | 88 | QJsonTreeWidget::~QJsonTreeWidget() 89 | { 90 | this->clear(); 91 | } 92 | 93 | bool QJsonTreeWidget::loadJson(const QString &path) 94 | { 95 | QFile file(path); 96 | file.open(QIODevice::ReadOnly); 97 | bool b = loadJson(file); 98 | file.close(); 99 | return b; 100 | } 101 | 102 | bool QJsonTreeWidget::loadJson(QIODevice &dev) 103 | { 104 | return loadJson(dev.readAll()); 105 | } 106 | 107 | bool QJsonTreeWidget::loadJson(const QByteArray &buf) 108 | { 109 | if (buf.isEmpty()) 110 | { 111 | setNotFoundInvalidOrEmptyError("loadJson","buf"); 112 | return false; 113 | } 114 | 115 | // parse 116 | bool ok; 117 | QVariantMap map = m_parser->parse(buf,&ok).toMap(); 118 | if (!ok) 119 | { 120 | m_error = tr("loadJson: JSON parser error: line %1, %2").arg(QVariant(m_parser->errorLine()).toString()).arg(m_parser->errorString()); 121 | return false; 122 | } 123 | 124 | return loadJson(map); 125 | } 126 | 127 | bool QJsonTreeWidget::loadJson(const QVariantMap &map) 128 | { 129 | return loadJsonInternal(map); 130 | } 131 | 132 | bool QJsonTreeWidget::saveJson(const QString &path, QJson::IndentMode indentmode, const QVariantMap& additional) 133 | { 134 | QFile file(path); 135 | bool b = file.open(QIODevice::WriteOnly); 136 | b = saveJson(file,indentmode,additional); 137 | file.close(); 138 | return b; 139 | } 140 | 141 | bool QJsonTreeWidget::saveJson(QIODevice &dev, QJson::IndentMode indentmode, const QVariantMap& additional) 142 | { 143 | QByteArray buf = saveJson(indentmode,additional); 144 | if (buf.isEmpty()) 145 | { 146 | setNotFoundInvalidOrEmptyError("saveJson","buf"); 147 | return false; 148 | } 149 | qint64 sz = dev.write(buf); 150 | if (sz != buf.size()) 151 | { 152 | m_error = tr("saveJson: error writing, requested %1, written %2, QIODevice error: %3").arg(QVariant(buf.size()).toString()).arg(QVariant(sz).toString()).arg(dev.errorString()); 153 | return false; 154 | } 155 | return true; 156 | } 157 | 158 | QByteArray QJsonTreeWidget::saveJson(QJson::IndentMode indentmode, const QVariantMap& additional) 159 | { 160 | m_serializer->setIndentMode(indentmode); 161 | QVariantMap m = m_root->child(0)->toMap(); 162 | foreach (QString key, additional.keys()) 163 | { 164 | m[key]=additional[key]; 165 | } 166 | 167 | return m_serializer->serialize(m); 168 | } 169 | 170 | int QJsonTreeWidget::jsonVersion(const QVariantMap map) const 171 | { 172 | int v = map.value("version",-1).toInt(); 173 | if (v == -1) 174 | return -1; 175 | 176 | return v; 177 | } 178 | 179 | void QJsonTreeWidget::resizeColumnsToContents() 180 | { 181 | for (int i=0; i < this->invisibleRootItem()->columnCount(); i++) 182 | { 183 | resizeColumnToContent(i); 184 | } 185 | } 186 | 187 | void QJsonTreeWidget::clear() 188 | { 189 | m_purgeList.clear(); 190 | m_purgeDescriptiveTags = false; 191 | m_model->clear(); 192 | } 193 | 194 | void QJsonTreeWidget::onDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) 195 | { 196 | Q_UNUSED(bottomRight); 197 | // since we emit onDataChanged with (index,index), topLeft is enough 198 | m_view->update(topLeft); 199 | } 200 | 201 | void QJsonTreeWidget::nextSelection() 202 | { 203 | QModelIndexList l = m_view->selectionModel()->selectedIndexes(); 204 | if (m_currentSelection.isValid()) 205 | { 206 | // get the next 207 | int idx = l.lastIndexOf(m_currentSelection); 208 | idx++; 209 | if (idx > (l.count() - 1)) 210 | { 211 | m_currentSelection = l.first(); 212 | } 213 | else 214 | { 215 | m_currentSelection = l.at(idx); 216 | } 217 | 218 | // scroll to the current selection 219 | m_view->scrollTo(m_currentSelection); 220 | } 221 | else 222 | { 223 | m_currentSelection = l.first(); 224 | 225 | // scroll to the current selection 226 | m_view->scrollTo(m_currentSelection); 227 | } 228 | } 229 | 230 | void QJsonTreeWidget::setNotFoundInvalidOrEmptyError(const QString &function, const QString &val) 231 | { 232 | m_error=tr("%1: ERROR not found, empty or invalid:\n%2").arg(function).arg(val); 233 | } 234 | 235 | void QJsonTreeWidget::keyPressEvent(QKeyEvent *event) 236 | { 237 | if (event->key() == Qt::Key_F3) 238 | nextSelection(); 239 | else if (event->key() == Qt::Key_C && event->modifiers() & Qt::ControlModifier) 240 | { 241 | // copy to clipboard requested 242 | QModelIndex idx = m_proxyModel->mapToSource(m_view->selectionModel()->selectedIndexes().at(0)); 243 | if (idx.isValid()) 244 | { 245 | QJsonTreeItem* it = m_model->itemByModelIndex(idx); 246 | if (it) 247 | QApplication::clipboard()->setText(it->text(idx.column())); 248 | } 249 | } 250 | } 251 | 252 | bool QJsonTreeWidget::loadJsonInternal(const QVariantMap& map) 253 | { 254 | this->clear(); 255 | 256 | if (map.isEmpty()) 257 | { 258 | setNotFoundInvalidOrEmptyError("loadJsonInternal","map"); 259 | return false; 260 | } 261 | 262 | int v = jsonVersion(map); 263 | if (v == -1) 264 | { 265 | setNotFoundInvalidOrEmptyError("loadJsonInternal","_version_"); 266 | return false; 267 | } 268 | if (v > m_maxVersion) 269 | { 270 | m_error = tr("loadJsonInternal: Unsupported JSON version: %1, maxversion: %2").arg(v).arg(m_maxVersion); 271 | return false; 272 | } 273 | 274 | QVariantMap maptouse = map; 275 | QVariantMap blob = map.value("_blob_",QVariantMap()).toMap(); 276 | if (!blob.isEmpty()) 277 | { 278 | // we use blob instead (for embedded trees into another map) 279 | maptouse = blob; 280 | } 281 | 282 | // create the root item. the root item is invisible, we use it only to store the headers hash. 283 | // so we need only _headers_ in it 284 | QString hdrstring = maptouse.value("_headers_",QString()).toString(); 285 | if (hdrstring.isEmpty()) 286 | { 287 | setNotFoundInvalidOrEmptyError("loadJsonInternal","_headers_"); 288 | return false; 289 | } 290 | 291 | QVariantMap m; 292 | m["_headers_"]=hdrstring; 293 | m_root = new QJsonTreeItem(this,0,m); 294 | if (!m_root->isValid()) 295 | { 296 | // something wrong with the invisible root item (probably header) 297 | QByteArray invalid = m_serializer->serialize(m_root->invalidMap()); 298 | setNotFoundInvalidOrEmptyError("buildModel",invalid); 299 | this->clear(); 300 | return false; 301 | } 302 | 303 | QJsonTreeItem* r = new QJsonTreeItem(this,m_root,maptouse); // this is the real root, 1st child of invisibleroot 304 | if (!m_root->isValid()) 305 | { 306 | // something wrong with the real root item (probably header) 307 | QByteArray invalid = m_serializer->serialize(m_root->invalidMap()); 308 | setNotFoundInvalidOrEmptyError("loadJsonInternal",invalid); 309 | this->clear(); 310 | return false; 311 | } 312 | m_root->appendChild(r); 313 | 314 | m_model->setRoot(m_root); 315 | m_proxyModel->setSourceModel(m_model); 316 | return true; 317 | 318 | } 319 | 320 | void QJsonTreeWidget::setSortingEnabled(bool enable) 321 | { 322 | m_view->setSortingEnabled(enable); 323 | if (!enable) 324 | { 325 | m_actionEnableSort->setVisible(true); 326 | m_actionDisableSort->setVisible(false); 327 | m_proxyModel->sort(-1); 328 | } 329 | else 330 | { 331 | // sorting enabled 332 | m_actionEnableSort->setVisible(false); 333 | m_actionDisableSort->setVisible(true); 334 | } 335 | } 336 | 337 | void QJsonTreeWidget::search(const QString& text) 338 | { 339 | this->expandAll(); 340 | m_proxyModel->setFilterRegExp(QRegExp(text,Qt::CaseInsensitive,QRegExp::FixedString)); 341 | searchInternal(); 342 | } 343 | 344 | void QJsonTreeWidget::search(const QRegExp& regex) 345 | { 346 | m_proxyModel->setFilterRegExp(regex); 347 | searchInternal(); 348 | } 349 | 350 | void QJsonTreeWidget::searchInternal() 351 | { 352 | m_view->selectionModel()->select(QModelIndex(),QItemSelectionModel::Clear); 353 | m_proxyModel->setFilterKeyColumn(-1); 354 | this->setFocus(); 355 | this->nextSelection(); 356 | } 357 | 358 | void QJsonTreeWidget::onActionLoad() 359 | { 360 | QString fname = QFileDialog::getOpenFileName(this, tr("Load JSON"),QString(),tr("JSON Files (*.json)")); 361 | if (!fname.isEmpty()) 362 | { 363 | loadJson(fname); 364 | this->expandAll(); 365 | this->resizeColumnToContent(0); 366 | } 367 | } 368 | 369 | void QJsonTreeWidget::onActionSave() 370 | { 371 | QString fname = QFileDialog::getSaveFileName(this, tr("Save JSON"),QString(),tr("JSON Files (*.json)")); 372 | if (!fname.isEmpty()) 373 | { 374 | saveJson(fname,QJson::IndentMinimum); 375 | } 376 | } 377 | 378 | void QJsonTreeWidget::onActionSaveHtml() 379 | { 380 | QString fname = QFileDialog::getSaveFileName(this, tr("Save HTML"),QString(),tr("HTML Files (*.html)")); 381 | if (!fname.isEmpty()) 382 | { 383 | toHtmlFile(fname); 384 | } 385 | } 386 | 387 | void QJsonTreeWidget::onActionEnableSort() 388 | { 389 | setSortingEnabled(true); 390 | } 391 | 392 | void QJsonTreeWidget::onActionDisableSort() 393 | { 394 | setSortingEnabled(false); 395 | } 396 | 397 | bool QJsonTreeWidget::validateItems(const QJsonTreeItem* item) const 398 | { 399 | // whole tree ? 400 | if (item == 0) 401 | { 402 | item = m_root; 403 | } 404 | 405 | QString failname; 406 | QString failcol; 407 | QString failval; 408 | if (!item->validateRegexp(&failcol,&failname,&failval)) 409 | { 410 | QMessageBox::warning(0,tr("Invalid input"), tr("Name: ") % failname % "\n" % tr("Column: ") % failcol % "\n" % tr("Text: ") % failval); 411 | return false; 412 | } 413 | if (item->childCount() > 0) 414 | { 415 | foreach (QJsonTreeItem* it, item->children()) 416 | { 417 | // recurse 418 | if (!validateItems(it)) 419 | return false; 420 | } 421 | } 422 | return true; 423 | } 424 | 425 | bool QJsonTreeWidget::findTag(const QString& tag, const QJsonTreeItem* item, QJsonTreeItem** found) const 426 | { 427 | if (item == 0) 428 | { 429 | item = m_root; 430 | } 431 | 432 | if (item->map().contains(tag)) 433 | { 434 | if (found) 435 | { 436 | *found = const_cast(item); 437 | } 438 | return true; 439 | } 440 | 441 | if (item->childCount() > 0) 442 | { 443 | foreach (QJsonTreeItem* it, item->children()) 444 | { 445 | // recurse 446 | if (findTag(tag,it,found)) 447 | return true; 448 | } 449 | } 450 | return false; 451 | } 452 | 453 | void QJsonTreeWidget::toHtmlEnd(QXmlStreamWriter* str, const QHash div) const 454 | { 455 | // close html 456 | str->writeEndElement(); // table 457 | if (!div.isEmpty()) 458 | { 459 | str->writeEndElement(); // div 460 | } 461 | str->writeEndElement(); // body 462 | str->writeEndElement(); // html 463 | delete str; 464 | } 465 | 466 | QXmlStreamWriter* QJsonTreeWidget::toHtmlStart(QString *dest, const QString &title, const QHash div, const QModelIndex& index) const 467 | { 468 | QXmlStreamWriter* str; 469 | str = new QXmlStreamWriter(dest); 470 | str->setAutoFormatting(true); 471 | 472 | // html header 473 | str->writeStartElement("html"); 474 | str->writeStartElement("head"); 475 | if (!title.isEmpty()) 476 | { 477 | str->writeTextElement("title",title); 478 | } 479 | str->writeEndElement(); // head 480 | 481 | // body 482 | str->writeStartElement("body"); 483 | if (!div.isEmpty()) 484 | { 485 | // div 486 | str->writeStartElement("div"); 487 | foreach (QString k, div.keys()) 488 | { 489 | str->writeAttribute(k,div[k]); 490 | } 491 | } 492 | 493 | // table 494 | str->writeStartElement("table"); 495 | str->writeAttribute("border","1"); 496 | str->writeStartElement("tr"); 497 | QJsonTreeItem* item = m_model->itemByModelIndex(QJsonSortFilterProxyModel::indexToSourceIndex(index)); 498 | for (int i=0; i < item->columnCount(); i++) 499 | { 500 | // headers 501 | str->writeTextElement("th",item->headerNameByIdx(i)); 502 | } 503 | str->writeEndElement(); // tr 504 | 505 | return str; 506 | } 507 | 508 | void QJsonTreeWidget::toHtmlInternal(QXmlStreamWriter *str, const QModelIndex &index) const 509 | { 510 | QJsonTreeItem* item = m_model->itemByModelIndex(QJsonSortFilterProxyModel::indexToSourceIndex(index)); 511 | 512 | // depth spaces 513 | int depth = item->depth(); 514 | QString spaces; 515 | for (int i=1; i < depth; i++) 516 | { 517 | spaces.append(" "); 518 | } 519 | 520 | str->writeStartElement("tr"); 521 | for (int i=0; i < item->columnCount(); i++) 522 | { 523 | QString s = item->map().value(item->headerTagByIdx(i),QString()).toString(); 524 | 525 | str->writeStartElement("td"); 526 | if (item->hasChildren()) 527 | { 528 | str->writeStartElement("b"); // parent bold 529 | } 530 | 531 | if (i == 0) 532 | { 533 | // column 0 has spacing 534 | if (!spaces.isEmpty()) 535 | { 536 | str->writeStartElement("pre"); 537 | str->writeCharacters(spaces); 538 | } 539 | } 540 | str->writeCharacters(s); 541 | if (!spaces.isEmpty() && i == 0) 542 | { 543 | str->writeEndElement(); // pre 544 | } 545 | if (item->hasChildren()) 546 | { 547 | str->writeEndElement(); // b 548 | } 549 | str->writeEndElement(); // td 550 | 551 | } 552 | str->writeEndElement(); // tr 553 | 554 | // recurse 555 | int i = 0; 556 | while (true) 557 | { 558 | QModelIndex idx = index.child(i,0); 559 | if (!idx.isValid()) 560 | break; 561 | toHtmlInternal(str,idx); 562 | i++; 563 | } 564 | } 565 | 566 | bool QJsonTreeWidget::toHtmlFile(const QString &path, const QString &title, const QHash div, QJsonTreeItem *item) const 567 | { 568 | QFile f (path); 569 | if (!f.open(QIODevice::WriteOnly)) 570 | return false; 571 | 572 | QString s = toHtml(title,div,item); 573 | if (s.isEmpty()) 574 | { 575 | f.close(); 576 | return false; 577 | } 578 | f.write(s.toLatin1()); 579 | f.close(); 580 | return true; 581 | } 582 | 583 | void QJsonTreeWidget::setHeaderMenuEnabled(bool enable) 584 | { 585 | if (enable) 586 | { 587 | m_view->header()->setContextMenuPolicy(Qt::ActionsContextMenu); 588 | } 589 | else 590 | { 591 | m_view->header()->setContextMenuPolicy(Qt::NoContextMenu); 592 | } 593 | } 594 | 595 | QString QJsonTreeWidget::toHtml(const QString &title, const QHash div, QJsonTreeItem *item) const 596 | { 597 | QModelIndex idx; 598 | 599 | if (!item) 600 | { 601 | // get the view's root 602 | idx = m_proxyModel->index(0,0,QModelIndex()); 603 | } 604 | else 605 | { 606 | // specific item 607 | idx = QJsonSortFilterProxyModel::indexToProxyIndex(m_model->indexByItem(item,0)); 608 | } 609 | 610 | QString s; 611 | QXmlStreamWriter* str = toHtmlStart(&s,title,div,idx); 612 | toHtmlInternal(str,idx); 613 | 614 | toHtmlEnd(str,div); 615 | return s; 616 | } 617 | -------------------------------------------------------------------------------- /libs/qjsontreewidget/qjsontreewidget.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of QJsonTreeWidget. 3 | 4 | Copyright (C) 2012 valerino 5 | 6 | QJsonTreeWidget is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | QJsonTreeWidget is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with QJsonTreeWidget. If not, see . 18 | */ 19 | 20 | #ifndef QJSONTREEWIDGET_H 21 | #define QJSONTREEWIDGET_H 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include "qjsontree_global.h" 30 | #include "qjsontreemodel.h" 31 | #include "qjsontreeitemdelegate.h" 32 | #include "qjsonsortfilterproxymodel.h" 33 | 34 | #define JSON_TREE_MAX_VERSION 3 // maximum supported JSON version by the library 35 | 36 | /** 37 | * @brief class to represent a JSON file using a tree widget and viceversa. 38 | * the format used to define the tree as a JSON is outlined here: https://www.te4i.com/confluence/display/H21/Configuration+JSON+format+%28rkmodv2%29 39 | * 40 | */ 41 | class QJSONTREE_EXPORT QJsonTreeWidget : public QWidget{ 42 | Q_OBJECT 43 | public: 44 | 45 | friend class QJsonTreeItem; 46 | friend class QJsonTreeModel; 47 | 48 | /** 49 | * @brief 50 | * 51 | * @param parent the parent object (optional) 52 | * @param f window flags (optional) 53 | */ 54 | QJsonTreeWidget(QWidget * parent = 0, Qt::WindowFlags f = 0 ); 55 | 56 | /** 57 | * @brief destructor 58 | * 59 | */ 60 | ~QJsonTreeWidget(); 61 | 62 | /** 63 | * @brief returns the optional QGridLayout where the user can add its own controls 64 | * 65 | * @return QGridLayout 66 | */ 67 | QGridLayout* optLayout() const { return m_optLayout; } 68 | 69 | /** 70 | * @brief returns detailed error 71 | * 72 | * @return const QString 73 | */ 74 | const QString error() const { return m_error; } 75 | 76 | /** 77 | * @brief 78 | * 79 | * @param path path to the JSON file 80 | * @return bool false on parser error, look at error() for detailed error string 81 | */ 82 | bool loadJson(const QString& path); 83 | 84 | /** 85 | * @brief 86 | * 87 | * @param dev a QIODevice (i.e. QFile) to read the JSON from 88 | * @return bool false on parser error, look at error() for detailed error string 89 | */ 90 | bool loadJson (QIODevice& dev); 91 | 92 | /** 93 | * @brief 94 | * 95 | * @param buf a QByteArray containing the JSON buffer 96 | * @return bool false on parser error, look at error() for detailed error string 97 | */ 98 | bool loadJson (const QByteArray& buf); 99 | 100 | /** 101 | * @brief 102 | * 103 | * @param buf a QVariant map 104 | * @return bool false if the map do not contain valid data for QJsonTreeWidget, look at error() for detailed error string 105 | */ 106 | bool loadJson (const QVariantMap& map); 107 | 108 | /** 109 | * @brief serializes the tree to a JSON file 110 | * 111 | * @param path path to the JSON file to be saved 112 | * @param indentmode one of the indentation mode defined in QJson::IndentMode 113 | * @param additional an optional additional map to be added 114 | * @return bool 115 | */ 116 | bool saveJson(const QString& path, QJson::IndentMode indentmode, const QVariantMap& additional = QVariantMap()); 117 | 118 | /** 119 | * @brief serializes the tree to a QIODevice file 120 | * 121 | * @param dev a QIODevice (i.e. QFile) 122 | * @param indentmode one of the indentation mode defined in QJson::IndentMode 123 | * @param additional an optional additional map to be added 124 | * @return bool 125 | */ 126 | bool saveJson (QIODevice& dev, QJson::IndentMode indentmode, const QVariantMap& additional = QVariantMap()); 127 | 128 | /** 129 | * @brief serializes the tree to a JSON buffer 130 | * 131 | * @param indentmode one of the indentation mode defined in QJson::IndentMode 132 | * @param additional an optional additional map to be added 133 | * @return QByteArray 134 | */ 135 | QByteArray saveJson (QJson::IndentMode indentmode, const QVariantMap& additional = QVariantMap()); 136 | 137 | /** 138 | * @brief saves the tree to a QVariantMap 139 | * 140 | * @return QVariantMap 141 | */ 142 | QVariantMap saveJson () const { if (!m_model) return QVariantMap(); return m_model->root()->toMap(); } 143 | 144 | /** 145 | * @brief expands all the items in the tree (warning: if the view contains lot of items, it may take time) 146 | * 147 | */ 148 | void expandAll() { m_view->expandAll(); } 149 | 150 | /** 151 | * @brief expands all the items in the tree to the given depth 152 | * 153 | * @param depth depths to expands the tree to 154 | */ 155 | void expandToDepth(int depth) { m_view->expandToDepth(depth); } 156 | 157 | /** 158 | * @brief collapse all items in the tree 159 | * 160 | */ 161 | void collapseAll() { m_view->collapseAll(); } 162 | 163 | /** 164 | * @brief resize all columns to their content size 165 | * 166 | */ 167 | void resizeColumnsToContents(); 168 | 169 | /** 170 | * @brief resize the given column to content size 171 | * 172 | * @param column the column to resize 173 | */ 174 | void resizeColumnToContent(int column) { m_view->resizeColumnToContents(column); } 175 | 176 | /** 177 | * @brief returns the root tree item (the whole tree itself), which is used only to store private data. 178 | * all the displayed items by the view are children of this item. this is to be consistent with other widget-based QT api. 179 | * @return QJsonTreeItem 180 | */ 181 | QJsonTreeItem* invisibleRootItem() const { if (!m_model) return 0; return m_model->root(); } 182 | 183 | /** 184 | * @brief clears the widget 185 | * 186 | */ 187 | void clear (); 188 | 189 | /** 190 | * @brief sets the model special flags to control how the view display the items 191 | * 192 | * @param QJsonTreeItem::SpecialFlag one or more special flags 193 | */ 194 | void setSpecialFlags(QJsonTreeItem::SpecialFlags flags) { if (m_model) m_model->setSpecialFlags(flags); } 195 | 196 | /** 197 | * @brief returns the current value of special flags 198 | * 199 | * @return QJsonTreeItem::SpecialFlags 200 | */ 201 | QJsonTreeItem::SpecialFlags specialFlags() const { if (!m_model) return 0; return m_model->specialFlags(); } 202 | 203 | /** 204 | * @brief set the last view's header section stretched or not 205 | * @param stretch true to stretch 206 | */ 207 | void setStretchLastSection(bool stretch) { m_view->header()->setStretchLastSection(stretch); } 208 | 209 | /** 210 | * @brief returns the view header 211 | * 212 | * return QHeaderView 213 | */ 214 | QHeaderView* header() { return m_view->header(); } 215 | 216 | /** 217 | * @brief returns the QJSON serializer 218 | * 219 | * return QJson::Serializer 220 | */ 221 | QJson::Serializer* serializer() const { return m_serializer; } 222 | 223 | /** 224 | * @brief returns the QJSON parser 225 | * 226 | * return QJson::Parser 227 | */ 228 | QJson::Parser* parser() const { return m_parser; } 229 | 230 | /** 231 | * @brief returns the version of JSON map to be represented (tag "version" in the map) 232 | * 233 | * @param map the JSON map 234 | * @return int 235 | */ 236 | int jsonVersion(const QVariantMap map) const; 237 | 238 | /** 239 | * @brief returns the maximum supported JSON tree version by the library 240 | * 241 | * @return int 242 | */ 243 | int jsonMaxSupportedVersion() const { return m_maxVersion; } 244 | 245 | /** 246 | * @brief enable or disable the dynamic sort/filtering 247 | * 248 | * @param enable view is sorted on insertion/deletion too, if sorting is enabled 249 | */ 250 | void setDynamicSortFiltering(bool enable) { m_proxyModel->setDynamicSortFilter(enable); } 251 | 252 | /** 253 | * @brief enable or disable sorting 254 | * 255 | * @param enable enable/disable sorting in the view 256 | */ 257 | void setSortingEnabled(bool enable); 258 | 259 | /** 260 | * @brief sets the sort order (ascending/descending) 261 | * 262 | * @param column column to set the sort order to 263 | * @param order the sort order (items are sorted in respect of the tree structure) 264 | */ 265 | void setSortOrder(int column, Qt::SortOrder order) { m_view->header()->setSortIndicator(column,order); } 266 | 267 | /** 268 | * @brief recursively search text in the tree 269 | * 270 | * @param text the text to find 271 | */ 272 | void search(const QString& text); 273 | 274 | /** 275 | * @brief recursively search text in the tree 276 | * 277 | * @param regex the regexp to match 278 | */ 279 | void search(const QRegExp& regex); 280 | 281 | /** 282 | * @brief enable the right-click "load from file" option 283 | * 284 | * @param enable to enable load 285 | */ 286 | void setLoadFromFileEnabled (bool enable) { m_actionLoad->setVisible(enable); } 287 | 288 | /** 289 | * @brief returns the state of the load-from-file action (visible/not visible) 290 | * 291 | * @return bool 292 | */ 293 | bool loadFromFileEnabled() const { return m_actionLoad->isVisible(); } 294 | 295 | /** 296 | * @brief returns the actions set in the view's header (to add custom actions) 297 | * 298 | * @return QList 299 | */ 300 | QList headerActions() const { return m_view->header()->actions(); } 301 | 302 | /** 303 | * @brief sets the list of tags to be purged when saving the tree 304 | * @param purgelist if not empty, an hash representing tags to strip off from saved JSON. true strips the item completely, including childs. false just strips the tag leaving the item 305 | */ 306 | void setPurgeListOnSave (const QHash& purgelist) { m_purgeList = purgelist; } 307 | 308 | /** 309 | * @brief returns the purge list to be applied on saving 310 | * 311 | * @return QHash 312 | */ 313 | const QHash purgeListOnSave () const { return m_purgeList; } 314 | 315 | /** 316 | * @brief enable editing on the widget 317 | * 318 | * @param enable to enable editing 319 | */ 320 | void setEditingEnabled(bool enable) { m_editing = enable; } 321 | 322 | /** 323 | * @brief returns if editing is enabled on the widget 324 | * 325 | * @return bool 326 | */ 327 | bool editingEnabled() const { return m_editing; } 328 | 329 | /** 330 | * @brief to purge all descriptive tags on save. this is similar to setPurgeListOnSave, but just purges only QJsonTreeWidget descriptive tags without stripping the 331 | * children of items containing the tags 332 | * 333 | * @param enable true to purge 334 | */ 335 | void setPurgeDescriptiveTagsOnSave(bool enable) { m_purgeDescriptiveTags = enable; } 336 | 337 | /** 338 | * @brief returns if purge descriptive tags is enabled on the widget 339 | * 340 | * @return bool 341 | */ 342 | bool purgeDescriptiveTags() const { return m_purgeDescriptiveTags; } 343 | 344 | 345 | /** 346 | * @brief check regular expressions set in the items having _regexp_ set (QLineEdit). returns false on the first mismatch 347 | * 348 | * @param item 0 for the whole tree, or a specific item 349 | * @return bool 350 | */ 351 | bool validateItems(const QJsonTreeItem* item = 0) const; 352 | 353 | /** 354 | * @brief returns true on the first time the specified tag is found 355 | * 356 | * @param tag tag to scan for, recursively 357 | * @param item 0 for the whole tree, or a specific item 358 | * @param found if not null, on return points to the item in which tag has been found 359 | * @return bool 360 | */ 361 | bool findTag(const QString& tag, const QJsonTreeItem *item = 0, QJsonTreeItem **found = 0) const; 362 | 363 | /** 364 | * @brief enable animations when expanding/collapsing the widget 365 | * 366 | * @param enable to enable 367 | */ 368 | void setAnimated(bool enable) { m_view->setAnimated(enable); } 369 | 370 | /** 371 | * @brief enable alternating row colors on the widget 372 | * 373 | * @param enable to enable 374 | */ 375 | void setAlternatingRowColors (bool enable) { m_view->setAlternatingRowColors(enable); } 376 | 377 | /** 378 | * @brief returns whether alternating row colors is set 379 | * 380 | * @return bool 381 | */ 382 | bool alternatingRowColors () const { return m_view->alternatingRowColors(); } 383 | 384 | /** 385 | * @brief hide the header in the widget 386 | * 387 | * @param hidden to hide 388 | */ 389 | void setHeaderHidden (bool hidden) { m_view->setHeaderHidden(hidden); } 390 | 391 | /** 392 | * @brief sets the background color for the column. note: any color manually set on the item takes precedence. 393 | * 394 | * @param tag the column JSON tag 395 | * @param color the color to be set 396 | */ 397 | void setColumnBackgroundColor (const QString& tag, const QColor& color) { m_model->setColumnBackgroundColor(tag,color); } 398 | 399 | /** 400 | * @brief returns the background color for the column 401 | * 402 | * @param tag the column JSON tag 403 | * @return QColor 404 | */ 405 | QColor columnBackgroundColor (const QString& tag) const { return m_model->columnBackgroundColor(tag); } 406 | 407 | /** 408 | * @brief sets the foreground color for the column. note: any color manually set on the item takes precedence. 409 | * 410 | * @param tag the column JSON tag 411 | * @param color the color to be set 412 | */ 413 | void setColumnForegroundColor (const QString& tag, const QColor& color) { m_model->setColumnForegroundColor(tag,color); } 414 | 415 | /** 416 | * @brief returns the foreground color for the column 417 | * 418 | * @param tag the column JSON tag 419 | * @return QColor 420 | */ 421 | QColor columnForegroundColor (const QString& tag) const { return m_model->columnForegroundColor(tag); } 422 | 423 | /** 424 | * @brief sets the font for the column. note: any font manually set on the item takes precedence 425 | * 426 | * @param tag the column JSON tag 427 | * @param font the font to be set 428 | */ 429 | void setColumnFont (const QString& tag, const QFont& font) { m_model->setColumnFont(tag,font); } 430 | 431 | /** 432 | * @brief returns the font for the column 433 | * 434 | * @param tag the column JSON tag 435 | * @return QFont 436 | */ 437 | QFont columnFont (const QString& tag) const { return m_model->columnFont(tag); } 438 | 439 | /** 440 | * @brief sets the background color for parent items. note: any color manually set on the item takes precedence. 441 | * 442 | * @param color the color to be set 443 | */ 444 | void setParentsBackgroundColor (const QColor& color) {m_model->setParentsBackgroundColor(color);} 445 | 446 | /** 447 | * @brief the background color for the parent items 448 | * 449 | * @return QColor 450 | */ 451 | QColor parentsBackgroundColor () const { return m_model->parentsBackgroundColor(); } 452 | 453 | /** 454 | * @brief sets the foreground color for parent items. note: any color manually set on the item takes precedence. 455 | * 456 | * @param color the color to be set 457 | */ 458 | void setParentsForegroundColor (const QColor& color) {m_model->setParentsForegroundColor(color);} 459 | 460 | /** 461 | * @brief the foreground color for the parent items 462 | * 463 | * @return QColor 464 | */ 465 | QColor parentsForegroundColor () const { return m_model->parentsForegroundColor(); } 466 | 467 | /** 468 | * @brief sets the font for parent items. note: any font manually set on the item takes precedence 469 | * 470 | * @param font the font to be set 471 | */ 472 | void setParentsFont (const QFont& font) { m_model->setParentsFont(font); } 473 | 474 | /** 475 | * @brief the font for the parent items 476 | * 477 | * @return QFont 478 | */ 479 | QFont parentsFont () const { return m_model->parentsFont(); } 480 | 481 | /** 482 | * @brief sets the background color for child items. note: any color manually set on the item takes precedence. 483 | * 484 | * @param color the color to be set 485 | */ 486 | void setChildsBackgroundColor (const QColor& color) {m_model->setChildsBackgroundColor(color);} 487 | 488 | /** 489 | * @brief the background color for the child items 490 | * 491 | * @return QColor 492 | */ 493 | QColor childsBackgroundColor () const { return m_model->childsBackgroundColor(); } 494 | 495 | /** 496 | * @brief sets the foreground color for child items. note: any color manually set on the item takes precedence. 497 | * 498 | * @param color the color to be set 499 | */ 500 | void setChildsForegroundColor (const QColor& color) {m_model->setChildsForegroundColor(color);} 501 | 502 | /** 503 | * @brief the foreground color for the parent items 504 | * 505 | * @return QColor 506 | */ 507 | QColor childsForegroundColor () const { return m_model->childsForegroundColor(); } 508 | 509 | /** 510 | * @brief sets the font for child items. note: any font manually set on the item takes precedence 511 | * 512 | * @param color the color to be set 513 | */ 514 | void setChildsFont (const QFont& font) { m_model->setChildsFont(font);} 515 | 516 | /** 517 | * @brief the font for child items 518 | * 519 | * @return QFont 520 | */ 521 | QFont childsFont () const { return m_model->childsFont(); } 522 | 523 | /** 524 | * @brief outputs the tree to html string 525 | * 526 | * @param title optional, the page title 527 | * @param div hash with optional "div" names and values 528 | * @param item 0 for the whole tree, or a specific item 529 | */ 530 | QString toHtml(const QString &title=QString(), const QHash div =QHash(), QJsonTreeItem *item=0) const; 531 | 532 | /** 533 | * @brief outputs the tree to html file 534 | * 535 | * @param path path to the destination html file 536 | * @param title optional, the page title 537 | * @param div hash with optional "div" names and values 538 | * @param item 0 for the whole tree, or a specific item 539 | * @return bool 540 | */ 541 | bool toHtmlFile(const QString& path, const QString& title = QString(), const QHash div = QHash(), QJsonTreeItem* item = 0) const; 542 | 543 | /** 544 | * @brief enables the menu (load/save/sort/savehtml) activated by rightclicking on the header 545 | * 546 | * @param enable enable menu 547 | */ 548 | void setHeaderMenuEnabled(bool enable); 549 | 550 | signals: 551 | /** 552 | * @brief connect to this signal to be notified of generic mouseclicks on the view 553 | * 554 | * @param column the clicked column index 555 | * @param row the clicked row index 556 | * @param jsontag the corresponding JSON tag at column,row 557 | * @param value the value displayed at column,row if any 558 | * @param item the corresponding QJsonTreeItem* at row (you can get the full map calling item->map()) 559 | */ 560 | void clicked (int column, int row, const QString& jsontag, const QVariant& value, const QJsonTreeItem* item); 561 | 562 | /** 563 | * @brief connect to this signal to be notified of mouseclicks on a pushbutton in the view (_button_ JSON tag) 564 | * essentially this is a shortcut for the above more complete signal 565 | * @param item the corresponding QJsonTreeItem* (you can get the full map calling item->map()) 566 | * @param jsontag the corresponding JSON tag at the position identified by column and row in the tree 567 | */ 568 | void clicked (const QJsonTreeItem* item, const QString& jsontag); 569 | 570 | private slots: 571 | void onDataChanged (const QModelIndex & topLeft, const QModelIndex & bottomRight ); 572 | void nextSelection(); 573 | void onActionLoad(); 574 | void onActionSave(); 575 | void onActionEnableSort(); 576 | void onActionDisableSort(); 577 | void onActionSaveHtml(); 578 | 579 | protected: 580 | QJsonSortFilterProxyModel* proxyModel() const { return m_proxyModel; } 581 | QTreeView* view() const { return m_view; } 582 | QJsonTreeModel* model() const { return m_model; } 583 | virtual void keyPressEvent(QKeyEvent *event); 584 | 585 | private: 586 | void searchInternal(); 587 | bool loadJsonInternal(const QVariantMap &map); 588 | void setNotFoundInvalidOrEmptyError(const QString &function, const QString &val); 589 | QXmlStreamWriter *toHtmlStart(QString *dest, const QString &title, const QHash div, const QModelIndex &index = QModelIndex()) const; 590 | void toHtmlEnd(QXmlStreamWriter* str, const QHash div = QHash()) const; 591 | void toHtmlInternal(QXmlStreamWriter *str, const QModelIndex& index = QModelIndex()) const; 592 | 593 | QTreeView* m_view; 594 | QGridLayout* m_optLayout; 595 | QJsonTreeModel* m_model; 596 | QJsonSortFilterProxyModel* m_proxyModel; 597 | QJsonTreeItem* m_root; 598 | QJsonTreeItemDelegate* m_delegate; 599 | QString m_error; 600 | QJson::Parser* m_parser; 601 | QJson::Serializer* m_serializer; 602 | QModelIndex m_currentSelection; 603 | QAction* m_actionLoad; 604 | QAction* m_actionSave; 605 | QAction* m_actionSaveHtml; 606 | QAction* m_actionEnableSort; 607 | QAction* m_actionDisableSort; 608 | QHash m_purgeList; 609 | bool m_purgeDescriptiveTags; 610 | bool m_editing; 611 | bool m_enableHdrMenu; 612 | int m_maxVersion; 613 | }; 614 | 615 | #endif // QJSONTREEWIDGET_H 616 | -------------------------------------------------------------------------------- /libs/qjsontreewidget/qjsontreewidget.pro: -------------------------------------------------------------------------------- 1 | #------------------------------------------------- 2 | # 3 | # Project created by QtCreator 2012-02-10T10:52:16 4 | # 5 | #------------------------------------------------- 6 | 7 | TARGET = qjsontreewidget 8 | TEMPLATE = lib 9 | DEFINES += QJSONTREEWIDGET_LIBRARY 10 | CONFIG += create_prl 11 | 12 | DESTDIR =lib 13 | 14 | SOURCES += qjsontreewidget.cpp \ 15 | qjsontreemodel.cpp \ 16 | qjsontreeitem.cpp \ 17 | qjsontreeitemdelegate.cpp \ 18 | qjsonsortfilterproxymodel.cpp 19 | 20 | HEADERS += qjsontreewidget.h \ 21 | qjsontreemodel.h \ 22 | qjsontreeitem.h \ 23 | qjsontreeitemdelegate.h \ 24 | qjsonsortfilterproxymodel.h 25 | 26 | INCLUDEPATH += ../qjson/include 27 | -------------------------------------------------------------------------------- /test/dialog.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "dialog.h" 4 | #include "ui_dialog.h" 5 | 6 | Dialog::Dialog(QWidget *parent) : 7 | QDialog(parent), 8 | ui(new Ui::Dialog) 9 | { 10 | ui->setupUi(this); 11 | 12 | // create the widget and add it to this dialog layout 13 | m_qjsw = new QJsonTreeWidget(this); 14 | ui->verticalLayout_2->addWidget(m_qjsw); 15 | 16 | // to catch pushbutton clicks 17 | connect (m_qjsw,SIGNAL(clicked(const QJsonTreeItem*,QString)),this,SLOT(onTreeButtonClicked(const QJsonTreeItem*,QString))); 18 | 19 | // load configuration at startup 20 | QTimer::singleShot(0,this,SLOT(loadCfg())); 21 | } 22 | 23 | Dialog::~Dialog() 24 | { 25 | delete ui; 26 | } 27 | 28 | void Dialog::loadCfg(const QString &fname) 29 | { 30 | bool b = m_qjsw->loadJson(fname); 31 | if (!b) 32 | { 33 | QMessageBox::critical(this,tr("Error"),m_qjsw->error()); 34 | } 35 | m_qjsw->expandAll(); 36 | m_qjsw->resizeColumnToContent(1); 37 | m_qjsw->resizeColumnToContent(2); 38 | m_qjsw->resizeColumnToContent(0); 39 | m_qjsw->setStretchLastSection(false); 40 | m_qjsw->setLoadFromFileEnabled(true); 41 | m_qjsw->setSortingEnabled(true); 42 | m_qjsw->setColumnForegroundColor("_desc_",QApplication::style()->standardPalette().mid().color()); 43 | QFont f; 44 | f.setItalic(true); 45 | m_qjsw->setColumnFont("_desc_",f); 46 | f.setBold(true); 47 | f.setItalic(false); 48 | m_qjsw->setParentsFont(f); 49 | m_lastLoaded = fname; 50 | } 51 | 52 | void Dialog::loadCfg() 53 | { 54 | QString fname (QApplication::applicationDirPath() % "/test.json"); 55 | loadCfg(fname); 56 | } 57 | 58 | void Dialog::on_honorReadOnlyCheckBox_toggled(bool checked) 59 | { 60 | checked ? (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() | QJsonTreeItem::HonorReadOnly)) : 61 | (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() & ~QJsonTreeItem::HonorReadOnly)); 62 | } 63 | 64 | void Dialog::on_honorHideCheckBox_toggled(bool checked) 65 | { 66 | checked ? (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() | QJsonTreeItem::HonorHide)) : 67 | (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() & ~QJsonTreeItem::HonorHide)); 68 | } 69 | 70 | void Dialog::on_treatROAsHideCheckBox_toggled(bool checked) 71 | { 72 | checked ? (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() | QJsonTreeItem::ReadOnlyHidesRow)) : 73 | (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() & ~QJsonTreeItem::ReadOnlyHidesRow)); 74 | } 75 | 76 | void Dialog::on_clearPushButton_clicked() 77 | { 78 | m_qjsw->clear(); 79 | } 80 | 81 | void Dialog::on_reloadPushButton_clicked() 82 | { 83 | loadCfg(m_lastLoaded); 84 | } 85 | 86 | void Dialog::onTreeButtonClicked(const QJsonTreeItem *item, const QString& jsontag) 87 | { 88 | QString fname = QFileDialog::getOpenFileName(0, tr("Select path"),QString(),tr("All files (*.*)")); 89 | if (!fname.isEmpty()) 90 | { 91 | const_cast(item)->setMapValue("value",fname); 92 | } 93 | } 94 | 95 | void Dialog::on_searchButton_clicked() 96 | { 97 | m_qjsw->search(ui->searchLineEdit->text()); 98 | } 99 | 100 | void Dialog::on_honorChildFontCheckbox_toggled(bool checked) 101 | { 102 | checked ? (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() | QJsonTreeItem::HonorChildsFont)) : 103 | (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() & ~QJsonTreeItem::HonorChildsFont)); 104 | } 105 | 106 | void Dialog::on_honorParentFontCheckbox_toggled(bool checked) 107 | { 108 | checked ? (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() | QJsonTreeItem::HonorParentsFont)) : 109 | (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() & ~QJsonTreeItem::HonorParentsFont)); 110 | } 111 | 112 | void Dialog::on_honorChildFgColorCheckBox_toggled(bool checked) 113 | { 114 | checked ? (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() | QJsonTreeItem::HonorChildsForegroundColor)) : 115 | (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() & ~QJsonTreeItem::HonorChildsForegroundColor)); 116 | } 117 | 118 | void Dialog::on_honorChildBgColorCheckBox_toggled(bool checked) 119 | { 120 | checked ? (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() | QJsonTreeItem::HonorChildsBackgroundColor)) : 121 | (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() & ~QJsonTreeItem::HonorChildsBackgroundColor)); 122 | } 123 | 124 | void Dialog::on_honorParentBgColorCheckBox_toggled(bool checked) 125 | { 126 | checked ? (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() | QJsonTreeItem::HonorParentsBackgroundColor)) : 127 | (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() & ~QJsonTreeItem::HonorParentsBackgroundColor)); 128 | } 129 | 130 | void Dialog::on_honorParentFgColorCheckBox_toggled(bool checked) 131 | { 132 | checked ? (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() | QJsonTreeItem::HonorParentsForegroundColor)) : 133 | (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() & ~QJsonTreeItem::HonorParentsForegroundColor)); 134 | } 135 | 136 | void Dialog::on_honorItemBgColorCheckBox_toggled(bool checked) 137 | { 138 | checked ? (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() | QJsonTreeItem::HonorItemBackgroundColor)) : 139 | (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() & ~QJsonTreeItem::HonorItemBackgroundColor)); 140 | } 141 | 142 | void Dialog::on_honorItemFgColorCheckBox_toggled(bool checked) 143 | { 144 | checked ? (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() | QJsonTreeItem::HonorItemForegroundColor)) : 145 | (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() & ~QJsonTreeItem::HonorItemForegroundColor)); 146 | } 147 | 148 | void Dialog::on_honorItemFontCheckBox_toggled(bool checked) 149 | { 150 | checked ? (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() | QJsonTreeItem::HonorItemFont)) : 151 | (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() & ~QJsonTreeItem::HonorItemFont)); 152 | } 153 | 154 | void Dialog::on_honorColumnFontCheckBox_toggled(bool checked) 155 | { 156 | checked ? (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() | QJsonTreeItem::HonorColumnFont)) : 157 | (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() & ~QJsonTreeItem::HonorColumnFont)); 158 | } 159 | 160 | void Dialog::on_honorColumnFgColorCheckBox_toggled(bool checked) 161 | { 162 | checked ? (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() | QJsonTreeItem::HonorColumnForegroundColor)) : 163 | (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() & ~QJsonTreeItem::HonorColumnForegroundColor)); 164 | 165 | } 166 | 167 | void Dialog::on_honorColumnBgColorCheckBox_toggled(bool checked) 168 | { 169 | checked ? (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() | QJsonTreeItem::HonorColumnBackgroundColor)) : 170 | (m_qjsw->setSpecialFlags(m_qjsw->specialFlags() & ~QJsonTreeItem::HonorColumnBackgroundColor)); 171 | 172 | } 173 | -------------------------------------------------------------------------------- /test/dialog.h: -------------------------------------------------------------------------------- 1 | #ifndef DIALOG_H 2 | #define DIALOG_H 3 | 4 | #include 5 | #include 6 | 7 | namespace Ui { 8 | class Dialog; 9 | } 10 | class Dialog : public QDialog 11 | { 12 | Q_OBJECT 13 | 14 | public: 15 | explicit Dialog(QWidget *parent = 0); 16 | ~Dialog(); 17 | 18 | private: 19 | Ui::Dialog *ui; 20 | void loadCfg(const QString& fname); 21 | QWidget *m_widget; 22 | QJsonTreeWidget* m_qjsw; 23 | QString m_lastLoaded; 24 | private slots: 25 | void loadCfg(); 26 | void on_honorReadOnlyCheckBox_toggled(bool checked); 27 | void on_honorHideCheckBox_toggled(bool checked); 28 | void on_treatROAsHideCheckBox_toggled(bool checked); 29 | void on_clearPushButton_clicked(); 30 | void on_reloadPushButton_clicked(); 31 | 32 | void onTreeButtonClicked(const QJsonTreeItem* item, const QString& jsontag); 33 | void on_searchButton_clicked(); 34 | void on_honorChildFontCheckbox_toggled(bool checked); 35 | void on_honorParentFontCheckbox_toggled(bool checked); 36 | void on_honorChildFgColorCheckBox_toggled(bool checked); 37 | void on_honorChildBgColorCheckBox_toggled(bool checked); 38 | void on_honorParentBgColorCheckBox_toggled(bool checked); 39 | void on_honorParentFgColorCheckBox_toggled(bool checked); 40 | void on_honorItemBgColorCheckBox_toggled(bool checked); 41 | void on_honorItemFgColorCheckBox_toggled(bool checked); 42 | void on_honorItemFontCheckBox_toggled(bool checked); 43 | void on_honorColumnFontCheckBox_toggled(bool checked); 44 | void on_honorColumnFgColorCheckBox_toggled(bool checked); 45 | void on_honorColumnBgColorCheckBox_toggled(bool checked); 46 | }; 47 | 48 | #endif // DIALOG_H 49 | -------------------------------------------------------------------------------- /test/dialog.ui: -------------------------------------------------------------------------------- 1 | 2 | 3 | Dialog 4 | 5 | 6 | 7 | 0 8 | 0 9 | 1778 10 | 603 11 | 12 | 13 | 14 | Dialog 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | Honor child background color 23 | 24 | 25 | true 26 | 27 | 28 | 29 | 30 | 31 | 32 | Honor child foreground color 33 | 34 | 35 | true 36 | 37 | 38 | 39 | 40 | 41 | 42 | Honor child font 43 | 44 | 45 | true 46 | 47 | 48 | 49 | 50 | 51 | 52 | Honor parent background color 53 | 54 | 55 | true 56 | 57 | 58 | 59 | 60 | 61 | 62 | Honor parent foreground color 63 | 64 | 65 | true 66 | 67 | 68 | 69 | 70 | 71 | 72 | Honor parent font 73 | 74 | 75 | true 76 | 77 | 78 | 79 | 80 | 81 | 82 | Treat readonly as 'hide whole row' 83 | 84 | 85 | 86 | 87 | 88 | 89 | Honor hide 90 | 91 | 92 | true 93 | 94 | 95 | 96 | 97 | 98 | 99 | Honor readonly 100 | 101 | 102 | true 103 | 104 | 105 | 106 | 107 | 108 | 109 | Honor item background color 110 | 111 | 112 | true 113 | 114 | 115 | 116 | 117 | 118 | 119 | Honor item foreground color 120 | 121 | 122 | true 123 | 124 | 125 | 126 | 127 | 128 | 129 | Honor item font 130 | 131 | 132 | true 133 | 134 | 135 | 136 | 137 | 138 | 139 | Honor column background color 140 | 141 | 142 | true 143 | 144 | 145 | 146 | 147 | 148 | 149 | Honor column foreground color 150 | 151 | 152 | true 153 | 154 | 155 | 156 | 157 | 158 | 159 | Honor column font 160 | 161 | 162 | true 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | Search 174 | 175 | 176 | 177 | 178 | 179 | 180 | testbutton1 181 | 182 | 183 | 184 | 185 | 186 | 187 | Search 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | reload 197 | 198 | 199 | 200 | 201 | 202 | 203 | clear 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | -------------------------------------------------------------------------------- /test/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "dialog.h" 3 | 4 | int main(int argc, char *argv[]) 5 | { 6 | QApplication a(argc, argv); 7 | Dialog w; 8 | w.show(); 9 | 10 | return a.exec(); 11 | } 12 | -------------------------------------------------------------------------------- /test/test.json: -------------------------------------------------------------------------------- 1 | { "_desc_" : "Configuration options", "name" : "Configuration", "version" : 3, "_headers_": "name:name:0,description:_desc_:1,value:value:2,value2:anothervalue:3,click:_button1_:4:draw,click2:_button2_:5:draw", "_children_" : [ 2 | { "_desc_" : "Tree sample", "name" : "tree1", "_widget_:value" : "Tree", "_children_" : [ 3 | { "_desc_" : "String sample", "name" : "foostring", "_regexp_:value" : ".+", "value" : "abcdefghijklmnopqrstuwxyz", "_widget_:value" : "QLineEdit" }, 4 | { "_desc_" : "Spinbox sample", "_valuemax_:value" : 200, "_valuemin_:value" : 50, "name" : "foocount", "value" : 100, "_widget_:value" : "QSpinBox" }, 5 | { "_desc_" : "Checkbox sample", "name" : "foocheckbox", "value" : true, "_widget_:value" : "QCheckBox" }, 6 | { "_desc_" : "Hidden sample", "_hide_":true, "name" : "foocheckbox2", "value" : true, "_widget_:value" : "QCheckBox" }, 7 | { "_desc_" : "Sample with hidden value", "name" : "foocheckbox3", "value" : true, "_widget_:value" : "QCheckBox", "anothervalue" : true, "_widget_:anothervalue" : "QCheckBox", "_hide_:anothervalue":true }, 8 | { "_desc_" : "Test button clicks", "name" : "testbutton1", "_button1_": "QPushButton,,clickme!", "_button2_": "QPushButton,,clickme2!" } 9 | ] }, 10 | { "_desc_" : "Another tree", "name" : "tree2", "_widget_:value" : "Tree", "_children_" : [ 11 | { "_desc_" : "A subtree", "name" : "tree3", "_widget_:value" : "Tree", "_children_" : [ 12 | { "_desc_" : "Another subtree", "name" : "tree4", "_widget_:value" : "Tree", "_children_" : [ 13 | { "_desc_" : "Combobox sample, readonly", "name" : "foocombo", "_readonly_:value" : true, "value" : "value1", "_valuelist_:value" : "value1,value2,value3", "_widget_:value" : "QComboBox" }, 14 | { "_desc_" : "Template sample", "name" : "footemplate", "_template_":true, "_mandatory_":true, "_widget_:value" : "Tree", "_children_" : [ 15 | { "_desc_" : "A string", "name" : "foostring", "_readonly_:value" : false, "_regexp_:value" : ".+", "value" : "1234567890", "_widget_:value": "QLineEdit" } 16 | ] }, 17 | { "_desc_" : "Template sample", "name" : "footemplate", "_widget_:value" : "Tree", "_children_" : [ 18 | { "_desc_" : "A string", "name" : "foostring", "_readonly_:value" : false, "_regexp_:value" : ".+", "value" : "bla,bla,bla", "_widget_:value": "QLineEdit" } 19 | ] } 20 | ] } 21 | ] } 22 | ] } 23 | ] } 24 | -------------------------------------------------------------------------------- /test/test.pro: -------------------------------------------------------------------------------- 1 | #------------------------------------------------- 2 | # 3 | # Project created by QtCreator 2012-02-10T15:13:08 4 | # 5 | #------------------------------------------------- 6 | 7 | QT += core gui 8 | 9 | TARGET = test 10 | TEMPLATE = app 11 | 12 | SOURCES += main.cpp\ 13 | dialog.cpp 14 | 15 | HEADERS += \ 16 | dialog.h 17 | 18 | FORMS += \ 19 | dialog.ui 20 | 21 | INCLUDEPATH += ../libs/qjsontreewidget \ 22 | ../libs/qjson/include 23 | 24 | LIBS += -L../libs/qjsontreewidget/lib -lqjsontreewidget 25 | LIBS += -L../libs/qjson/lib -lqjson 26 | 27 | jsonfiles.files = *.json 28 | jsonfiles.path = $$OUT_PWD/$(DESTDIR) 29 | INSTALLS += jsonfiles 30 | 31 | POST_TARGETDEPS += install 32 | 33 | OTHER_FILES += \ 34 | rkcfg.json \ 35 | test.json 36 | 37 | --------------------------------------------------------------------------------