Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt for Python
  4. VPN connect app. PyQt5. how to display output in second display?
Forum Updated to NodeBB v4.3 + New Features

VPN connect app. PyQt5. how to display output in second display?

Scheduled Pinned Locked Moved Solved Qt for Python
28 Posts 5 Posters 3.7k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Al3x
    21 Sept 2024, 20:55

    Ugh this @Axel-Spoerl guy. Had a bad day looks like.
    He closed my topic "for waisting time" and directed it to this Topic,. so i guess i ask here... :) not that its anything to do with this Topic..
    #############################
    Im trying to create a QTree that displays XML content. Basic xml that has multiple entries for various VPN ips.
    The script as is now works but thats with the actual 'Data' hardcoded inside the script. I need to read an xml and display it equivalent to how it does now.
    Ive read a few articles but im struggling to get it working..
    Could someone give me some pointers?
    Cheers!

    import sys
    from PyQt5 import QtCore, QtGui, QtWidgets
    from PyQt5.QtWidgets import QTreeWidgetItem
    
    #import xml.etree.ElementTree as ET
    #tree = ET.parse('data.xml')
    #root = tree.getroot()
    
    class Widget(QtWidgets.QWidget):
       def __init__(self, parent=None):
           super(Widget, self).__init__(parent)
           lay = QtWidgets.QVBoxLayout(self)
           tree = QtWidgets.QTreeWidget()
           tree.setColumnCount(3)
           tree.setHeaderLabels(["VPN", "2", "3"])
           lay.addWidget(tree)
    
    
    
    #########################################################
    ## new - not working
    #        f = open("data.xml", 'r').read()
    #        self.printtree(f)
    #
    #    def printtree(self, s):
    #        tree = ET.fromstring(s)
    #        a=QTreeWidgetItem([tree.tag])
    #        self.tree.addtTopLevelItems(a)
    #
    #        def displaytree(a,s):
    #            for child in s:
    #                branch=QTreeWidgetItem([child.tag])
    #                a.addChild(branch)
    #                displaytree(branch,child)
    #        displaytree(a,tree)
    
    ###########################################################
    ## new - not working
    
    
    ## working
           data = {
           "USA": ["18.122.x.xx.ovpn", "0.22.0.0.ovpn", "11.0.0.0.ovpn"],
           "Europe": ["77.0.0.0.ovpn", "66.0.0.0.ovpn"],
           "Asia": ["99.0.0.0.ovpn","0.99.0.0.ovpn"]}
    
           items = []
           for key, values in data.items():
               item = QTreeWidgetItem([key])
               for value in values:
                   ext = value.split(".")[-1].upper()
                   child = QTreeWidgetItem([value, ext])
                   item.addChild(child)
               items.append(item)
           tree.insertTopLevelItems(0, items)
    
           tree.expandAll()
           tree.itemClicked.connect(self.onItemClicked)
    
       @QtCore.pyqtSlot(QtWidgets.QTreeWidgetItem, int)
       def onItemClicked(self, it, col):
           print(it.text(col))
    ## working ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    
    
    
    #####################################################################
    if __name__ == '__main__':
       import sys
    
       app = QtWidgets.QApplication(sys.argv)
       w = Widget()
       w.show()
       sys.exit(app.exec_())
    
    
    
    J Offline
    J Offline
    JonB
    wrote on 22 Sept 2024, 08:20 last edited by JonB
    #18

    @Al3x
    I don't know whether your goal/requirement is to use XML or JSON. The code you show is actually just Python (objects, arrays), which is pretty close to JSON. If that is all the data there is you don't really need more than JSON. You have to decide whether you want JSON or XML.

    If you want to use Qt classes there is QJsonDocument for JSON or, as @Axel-Spoerl said, QDomDocument for XML. Python also has its own classes/code for both of these, if you want to use them you are on your own.

    If your issue is about wanting to read from XML/JSON file instead of hard-coding then both of those, whether Qt's or Python's, have methods to read/create a complete document from an external file.

    Both XML and JSON produce a hierarchical tree structure. QTreeView can display a hierarchical tree. It needs a model, derived from QAbstractItemModel. You can either take the simpler but less efficient route of copying your data into, say, a QStandardItemModel, which can create a hierarchical tree model suitable for use with a QTreeView (maybe see https://www.qtcentre.org/threads/44877-Convert-XML-to-QTreeView), or you can take the more ambitious route of writing your own subclass of QAbstractItemModel which links directly to your in-memory JSON or XML model, whether that is with Qt classes or Python ones. For example, https://forum.qt.io/topic/49771/jsonmodel-for-qtreeview appears to give a couple of links where someone has done so for JSON.

    For the code you appear to have started on but commented out. It uses some Python class import xml.etree.ElementTree as ET. But nobody here knows anything about what structure that Python produces and what you have to do with it to populate a QTreeWidget. If you say "it does not work" you might step through your code in Python debugger and diagnose what is going on.

    If nothing else, in the code you show self.tree.addtTopLevelItems(a) is simply wrong and will produce an error, even if self.tree existed. Which as per your __init__() it does not, you have no self.tree.

    (And btw don't use the same variable name, tree, for two quite different things: the Qt QTreeWidget and whatever parsed tree structure xml.etree.ElementTree produces. It simply leads to confusion and potential mishaps. Use different, meaningful variable names.)

    A 1 Reply Last reply 22 Sept 2024, 14:31
    0
    • J JonB
      22 Sept 2024, 08:20

      @Al3x
      I don't know whether your goal/requirement is to use XML or JSON. The code you show is actually just Python (objects, arrays), which is pretty close to JSON. If that is all the data there is you don't really need more than JSON. You have to decide whether you want JSON or XML.

      If you want to use Qt classes there is QJsonDocument for JSON or, as @Axel-Spoerl said, QDomDocument for XML. Python also has its own classes/code for both of these, if you want to use them you are on your own.

      If your issue is about wanting to read from XML/JSON file instead of hard-coding then both of those, whether Qt's or Python's, have methods to read/create a complete document from an external file.

      Both XML and JSON produce a hierarchical tree structure. QTreeView can display a hierarchical tree. It needs a model, derived from QAbstractItemModel. You can either take the simpler but less efficient route of copying your data into, say, a QStandardItemModel, which can create a hierarchical tree model suitable for use with a QTreeView (maybe see https://www.qtcentre.org/threads/44877-Convert-XML-to-QTreeView), or you can take the more ambitious route of writing your own subclass of QAbstractItemModel which links directly to your in-memory JSON or XML model, whether that is with Qt classes or Python ones. For example, https://forum.qt.io/topic/49771/jsonmodel-for-qtreeview appears to give a couple of links where someone has done so for JSON.

      For the code you appear to have started on but commented out. It uses some Python class import xml.etree.ElementTree as ET. But nobody here knows anything about what structure that Python produces and what you have to do with it to populate a QTreeWidget. If you say "it does not work" you might step through your code in Python debugger and diagnose what is going on.

      If nothing else, in the code you show self.tree.addtTopLevelItems(a) is simply wrong and will produce an error, even if self.tree existed. Which as per your __init__() it does not, you have no self.tree.

      (And btw don't use the same variable name, tree, for two quite different things: the Qt QTreeWidget and whatever parsed tree structure xml.etree.ElementTree produces. It simply leads to confusion and potential mishaps. Use different, meaningful variable names.)

      A Offline
      A Offline
      Al3x
      wrote on 22 Sept 2024, 14:31 last edited by
      #19

      @JonB
      Thanks for the lengthy reply!! This i class as an answer, as oppose to through-ing out a link and saying "go read it all".

      No, what i still very much wish to do is use XML. DOM from reading is old and is more mem/cpu intensive. Whats your take on that?

      The script that i have is using ElementTree, its opening and reading the XML succesfully. i can also write to it succesfully
      And i can print it to string successfully:

      XMLtoStr = ET.tostring(root, encoding='utf8').decode('utf8')
      
      

      The problem is i cant manage to print into the Tree!
      Im using Qwidget.
      So perhaps thats the problem? -i should use QTreeView? with a model?

      This is the script now, if you run it, you will see it print the XML in the terminal, but it doesnt print it in the UI widget.

      tree.py

      import sys
      from PyQt5 import QtCore, QtGui, QtWidgets
      from PyQt5.QtWidgets import QTreeWidgetItem
      import xml.etree.ElementTree as ET
      ## access and set root for XML file
      tree = ET.parse('data.xml')
      root = tree.getroot()
      
      class Widget(QtWidgets.QWidget):
          def __init__(self):
              super(Widget, self).__init__()
              lay = QtWidgets.QVBoxLayout(self)
              tree = QtWidgets.QTreeWidget()
              tree.setColumnCount(3)
              tree.setHeaderLabels(["VPN", "2", "3"])
              lay.addWidget(tree)
              #self.tree = QTreeView()
              XMLtoStr = ET.tostring(root, encoding='utf8').decode('utf8')
              #self.printtree(f)
      
      ## print XML data in the file to string
      XMLtoStr = ET.tostring(root, encoding='utf8').decode('utf8')
      print(XMLtoStr)
      
      
      def printtree(self, s):
          #tree = ET.fromstring(s)
          tree = ET.tostring(root, encoding='utf8').decode('utf8')
      
          a = QTreeWidgetItem([tree.tag])
          self.tree.addtTopLevelItems(a)
      
          def displaytree(a,s):
              for child in s:
                  branch = QTreeWidgetItem([child.tag])
                  a.addChild(branch)
                  displaytree(branch,child)
              if s.text is not None:
                  content=s.text
                  a.addChild(QTreeWidgetItem([content]))
      
      
          displaytree(a,tree)
      
      
      #####################################################################
      if __name__ == '__main__':
          import sys
      
          app = QtWidgets.QApplication(sys.argv)
          w = Widget()
          w.show()
          sys.exit(app.exec_())
      
      

      data.xml

      <?xml version="1.0" encoding="UTF-8"?>
      <catalog>
          <vpn id="vpn01">
              <config>1.1.1.1.ovpn</config>
              <ip>1.1.1.1</ip>
              <port>443</port>
              <protocol>TCP</protocol>
              <country>US</country>
              <details>
              'info....'
            </details>
          </vpn>
          <vpn id="vpn02">
              <config>1.1.1.1.ovpn</config>
              <ip>1.1.1.1</ip>
              <port>443</port>
              <protocol>TCP</protocol>
              <country>US</country>
              <details>
              'info....'
            </details>
          </vpn>
          <vpn id="vpn03">
              <config>1.1.1.1.ovpn</config>
              <ip>1.1.1.1</ip>
              <port>443</port>
              <protocol>TCP</protocol>
              <country>US</country>
              <details>
              'info....'
            </details>
          </vpn>
      
      </catalog>
      
      

      Im still strugling to get to grips with QT
      Many thanks!

      1 Reply Last reply
      0
      • A Offline
        A Offline
        Axel Spoerl
        Moderators
        wrote on 22 Sept 2024, 14:43 last edited by
        #20

        I would definitively use a QTreeView and implement a model to view the XML tree.
        You can have a look a the document viewer example, to see how this can be implemented. It's in C++ and has a JSON viewer, but the principle is the same.

        Software Engineer
        The Qt Company, Oslo

        A 1 Reply Last reply 22 Sept 2024, 15:38
        0
        • A Axel Spoerl
          22 Sept 2024, 14:43

          I would definitively use a QTreeView and implement a model to view the XML tree.
          You can have a look a the document viewer example, to see how this can be implemented. It's in C++ and has a JSON viewer, but the principle is the same.

          A Offline
          A Offline
          Al3x
          wrote on 22 Sept 2024, 15:38 last edited by
          #21

          @Axel-Spoerl
          So would you care to share how you would do this?
          Im trying to do this in Python and XML.
          You think me being new to QT and python that a C++ example is going to help me alot?

          1 Reply Last reply
          0
          • A Offline
            A Offline
            Axel Spoerl
            Moderators
            wrote on 22 Sept 2024, 17:26 last edited by
            #22

            There is no example in our library, that demonstrates how to implement a QAbstractItemModel subclass in Python and I usually don't work with Python. This forum mainly offers support, when someone is stuck, something is unclear or even wrong in our library. It happens once in a while, that somebody asks for a concrete solution to a specific problem like yours - and gets it.
            But that's not a guarantee, not something you can expect. Everybody around here contributes to the forum in their free time, me included - even though I am employed by Qt.

            That said, implementing such a model is not a trivial task. Implementing it for XML even less. That's why I suggested you to go with JSON. The document viewer example I mentioned does exactly this. If you know a bit of Python, you will probably understand the mechanisms by reading the C++ code. Then there is ChatGPT and other tools, which can help you accomplish that.

            It doesn't help that you insult me in private messages of being a joker and an old man.
            It's forgiven, it probably happened in a wave of expectations to receive a ready made solution, and the frustration of not getting it.
            Please re-consider this attitude.

            Software Engineer
            The Qt Company, Oslo

            1 Reply Last reply
            1
            • A Offline
              A Offline
              Al3x
              wrote on 22 Sept 2024, 18:45 last edited by Al3x
              #23

              Yes, precisely, i am stuck,and hence the post (again).
              Hence the last post that i wish to use XML.
              ChatGPT and other tools. ha Youre a real Joker! arent you? ......circus coming!

              If you feel insulted by my general comment(PM), thats your problem, sorry but, if you write to me in a chaotic matter, dont expect a pleasant response. You should know better as a Moderator! Take it to ur psychologist or mom/dad

              and it certainly does not append to some wave of expectation to do the code for me!
              you have given no kind of direction other than misc links.

              If you dont have a solution to my post, dont post at all!

              J 1 Reply Last reply 23 Sept 2024, 06:11
              0
              • A Al3x
                22 Sept 2024, 18:45

                Yes, precisely, i am stuck,and hence the post (again).
                Hence the last post that i wish to use XML.
                ChatGPT and other tools. ha Youre a real Joker! arent you? ......circus coming!

                If you feel insulted by my general comment(PM), thats your problem, sorry but, if you write to me in a chaotic matter, dont expect a pleasant response. You should know better as a Moderator! Take it to ur psychologist or mom/dad

                and it certainly does not append to some wave of expectation to do the code for me!
                you have given no kind of direction other than misc links.

                If you dont have a solution to my post, dont post at all!

                J Offline
                J Offline
                jsulm
                Lifetime Qt Champion
                wrote on 23 Sept 2024, 06:11 last edited by
                #24

                @Al3x Please stop writing rude posts and read and follow https://forum.qt.io/topic/113070/qt-code-of-conduct

                https://forum.qt.io/topic/113070/qt-code-of-conduct

                1 Reply Last reply
                3
                • A Offline
                  A Offline
                  Al3x
                  wrote on 25 Sept 2024, 13:10 last edited by
                  #25

                  Thats great the Code of Conduct! im all for it! But i dislike @Axel-Spoerl! his energy is very negative!
                  When you begin your first post in an arrogant matter and give a vaugue answer and no explanation . And then get mad at my words and close the topic saying im waisting time! ---Get outta here!! And Then hes still writing to this topic(even tho im waisting his time! according to him!) .
                  ?

                  1 Reply Last reply
                  0
                  • A Offline
                    A Offline
                    Al3x
                    wrote on 25 Sept 2024, 18:46 last edited by
                    #26

                    and then... be a donkey like he is and tell me to use ChatGPT. Because hes an ignorant fool! and because the man can not answer his own answers.. its deplorable! WaisteMan! its the real definition of a Real WaisteMan!
                    I came to congretate in peace, but its been turned around thanks to this grow man maloquee . So much for grown men? Looks like a man in a skirt giving orders of no succession...
                    "Software Enginner" yea why not!

                    Rude comes with the turff.
                    Dont blame me for someone else's stupidity!

                    C J 2 Replies Last reply 26 Sept 2024, 04:17
                    0
                    • A Al3x
                      25 Sept 2024, 18:46

                      and then... be a donkey like he is and tell me to use ChatGPT. Because hes an ignorant fool! and because the man can not answer his own answers.. its deplorable! WaisteMan! its the real definition of a Real WaisteMan!
                      I came to congretate in peace, but its been turned around thanks to this grow man maloquee . So much for grown men? Looks like a man in a skirt giving orders of no succession...
                      "Software Enginner" yea why not!

                      Rude comes with the turff.
                      Dont blame me for someone else's stupidity!

                      C Online
                      C Online
                      Christian Ehrlicher
                      Lifetime Qt Champion
                      wrote on 26 Sept 2024, 04:17 last edited by
                      #27

                      @Al3x Please stop insulting other people and follow the Forum guidlines and Code of Conduct. or search another forum where insults on other people are tolerated - here it's for sure not.

                      Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
                      Visit the Qt Academy at https://academy.qt.io/catalog

                      1 Reply Last reply
                      4
                      • A Al3x
                        25 Sept 2024, 18:46

                        and then... be a donkey like he is and tell me to use ChatGPT. Because hes an ignorant fool! and because the man can not answer his own answers.. its deplorable! WaisteMan! its the real definition of a Real WaisteMan!
                        I came to congretate in peace, but its been turned around thanks to this grow man maloquee . So much for grown men? Looks like a man in a skirt giving orders of no succession...
                        "Software Enginner" yea why not!

                        Rude comes with the turff.
                        Dont blame me for someone else's stupidity!

                        J Offline
                        J Offline
                        jsulm
                        Lifetime Qt Champion
                        wrote on 26 Sept 2024, 05:16 last edited by
                        #28

                        @Al3x said in VPN connect app. PyQt5. how to display output in second display?:

                        Because hes an ignorant fool!

                        I already told you to stop to behave this way.
                        You will be banned if you continue to insult other people.
                        Last warning...

                        https://forum.qt.io/topic/113070/qt-code-of-conduct

                        1 Reply Last reply
                        2

                        27/28

                        26 Sept 2024, 04:17

                        • Login

                        • Login or register to search.
                        27 out of 28
                        • First post
                          27/28
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • Users
                        • Groups
                        • Search
                        • Get Qt Extensions
                        • Unsolved