есть ли функция для заполнения древовидного представления pyqt5 данными файла json - PullRequest
0 голосов
/ 18 июня 2020
import sys
import json
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtWidgets import QInputDialog, QLineEdit
from PyQt5.QtCore import Qt, QUrl
import traceback

Ui_MainWindow, QtBaseClass = uic.loadUiType('guis/financial.ui')
ledger_view, QtBaseClass = uic.loadUiType('guis/ledger.ui')
analysis_view, QtBaseClass = uic.loadUiType('guis/analysis.ui')
class ListView(QtWidgets.QTreeView):
    def __init__(self, *args, **kwargs):
        super(ListView, self).__init__(*args, **kwargs)
        self.setModel(QtGui.QStandardItemModel(self))
        self.model().setColumnCount(2)
        self.setRootIsDecorated(False)
        self.setAllColumnsShowFocus(True)
        self.setSelectionBehavior(
            QtWidgets.QAbstractItemView.SelectRows)
        self.setHeaderHidden(True)
        self.header().setStretchLastSection(False)
        self.header().setSectionResizeMode(
            0, QtWidgets.QHeaderView.Stretch)
        self.header().setSectionResizeMode(
            1, QtWidgets.QHeaderView.ResizeToContents)

 def addItem(self, key, value):
    first = QtGui.QStandardItem(key)
    second = QtGui.QStandardItem(value)
    second.setTextAlignment(QtCore.Qt.AlignRight)
    self.model().appendRow([first, second])
class Ledger(QtWidgets.QWidget, ledger_view):
    def __init__(self):
        super(Ledger, self).__init__()
        self.setupUi(self)
        self.hide()
class Analysis(QtWidgets.QWidget, analysis_view):
    def __init__(self):
        super(Analysis, self).__init__()
        self.setupUi(self)
        self.hide()
        self.getURLButton.clicked.connect(self.add)
    def add(self):
        try:
            self.webView.load(QUrl(self.urlBox.text()))
        except Exception as e:
            traceback.print_exc()
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        try:
            super(MainWindow, self).__init__()
            self.setupUi(self)

            #~~This needs to be fixed immediately here...~~~~
            self.income_view = ListView(self)
            self.expenses_view = ListView(self)
            self.assets_view = ListView(self)
            self.liabilities_view = ListView(self)
            self.opportunity_view = ListView(self)
            self.load('income')
        except Exception:
            traceback.print_exc()

        self.load('expenses')
        self.load('assets')
        self.load('liabilities')
        self.addButton.clicked.connect(self.addTransaction)
        self.analyzeButton.clicked.connect(self.analyze)


    def addTransaction(self):
        try:
            ledger.show()
            ledger.move(415,150)
        except Exception as e:
            traceback.print_exc()

    def analyze(self):
        try:
            analysis.show()
            analysis.move(313,150)
        except Exception as e:
            traceback.print_exc()

    def getComboSelection(self):
        text = str(self.comboBox.currentText())
        if text and text is not '':
            return text

    def load(self, data):
       try:
           if data == 'income':
                with open(f'data/{data}.db', 'r') as f:
                   content = json.load(f)
                   for item in content['Income']:
                       key = list(item.keys())[0]
                       if isinstance(item[key], list):
                           for i in item[key]:
                               keys = list(i.keys())[0]
                               self.income_view.addItem(keys, str(i[keys]))
                       else:
                           self.income_view.addItem(key, str(item[key]))
           elif data == 'expenses':
                with open(f'data/{data}.db', 'r') as f:
                   content = json.load(f)
                   for item in content['Expenses']:
                       key = list(item.keys())[0]
                       if isinstance(item[key], list):
                           for i in item[key]:
                               keys = list(i.keys())[0]
                               self.expenses_view.addItem(keys, str(i[keys]))
                       else:
                           self.expenses_view.addItem(key, str(item[key]))
           elif data == 'assets':
                with open(f'data/{data}.db', 'r') as f:
                   content = json.load(f)
                   for item in content['Assets']:
                       key = list(item.keys())[0]
                       if isinstance(item[key], list):
                           for i in item[key]:
                               keys = list(i.keys())[0]
                               self.assets_view.addItem(keys, str(i[keys]))
                       else:
                           self.assets_view.addItem(key, str(item[key]))
           elif data == 'liabilities':
                with open(f'data/{data}.db', 'r') as f:
                   content = json.load(f)
                   for item in content['Liabilities']:
                       key = list(item.keys())[0]
                       if isinstance(item[key], list):
                           for i in item[key]:
                               keys = list(i.keys())[0]
                               self.liabilities_view.addItem(keys, str(i[keys]))
                       else:
                           self.liabilities_view.addItem(key, str(item[key]))
           elif data == 'opportunities':
                pass
       except Exception:
           traceback.print_exc()
    def save(self, data):
        with open(f'data/{data}.db', 'w') as file:
            if data == 'income':
                content = json.dump(self.income_model.income, file)
            elif data == 'expenses':
                content = json.dump(self.expense_model.expenses, file)
            elif data == 'assets':
                content = json.dump(self.asset_model.assets, file)
            elif data == 'liabilities':
                content = json.dump(self.liability_model.liabilities, file)
            elif data == 'opportunities':
                content = json.dump(self.opps_model.opportunities, file)


app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
ledger = Ledger()
analysis = Analysis()
window.move(300,100)
window.show()
app.exec_()

Мне просто нужно получить данные, которые хранятся в json отформатированном файле, для отображения с соответствующими полями просмотра, которые находятся в файле ui. Я нашел одно решение, но оно работает только с Qwidget, а не с объектом Qmainwindow. Я смог заставить его работать, создав подкласс Qtreeview в виде списка и перезаписав метод addItem. Кажется, я не могу заставить его работать и загружать данные из файлов json для отображения. доход.db содержит данные отчета о прибылях и убытках, которые необходимо прочитать для заполнения объекта treeview yield_view, который находится в файле ui. Конечно, приветствуется любая помощь.

Ниже находится файл financial.ui.

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>mainWindow</class>
 <widget class="QMainWindow" name="mainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>1060</width>
    <height>878</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <property name="unifiedTitleAndToolBarOnMac">
   <bool>true</bool>
  </property>
  <widget class="QWidget" name="centralwidget">
   <widget class="QLineEdit" name="total_passive">
    <property name="geometry">
     <rect>
      <x>550</x>
      <y>40</y>
      <width>151</width>
      <height>41</height>
     </rect>
    </property>
    <property name="toolTip">
     <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Total Passive&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
    </property>
    <property name="inputMask">
     <string/>
    </property>
    <property name="text">
     <string/>
    </property>
   </widget>
   <widget class="QLineEdit" name="cash_flow">
    <property name="geometry">
     <rect>
      <x>550</x>
      <y>440</y>
      <width>151</width>
      <height>41</height>
     </rect>
    </property>
    <property name="toolTip">
     <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Cash Flow&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
    </property>
    <property name="text">
     <string/>
    </property>
   </widget>
   <widget class="QLineEdit" name="total_income">
    <property name="geometry">
     <rect>
      <x>550</x>
      <y>190</y>
      <width>151</width>
      <height>41</height>
     </rect>
    </property>
    <property name="toolTip">
     <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Total Income&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
    </property>
    <property name="text">
     <string/>
    </property>
   </widget>
   <widget class="QLineEdit" name="total_expenses">
    <property name="geometry">
     <rect>
      <x>550</x>
      <y>370</y>
      <width>151</width>
      <height>41</height>
     </rect>
    </property>
    <property name="toolTip">
     <string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;Total Expenses&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
    </property>
    <property name="text">
     <string/>
    </property>
   </widget>
   <widget class="QPushButton" name="addButton">
    <property name="geometry">
     <rect>
      <x>720</x>
      <y>500</y>
      <width>99</width>
      <height>27</height>
     </rect>
    </property>
    <property name="text">
     <string>Add</string>
    </property>
   </widget>
   <widget class="QPushButton" name="analyzeButton">
    <property name="geometry">
     <rect>
      <x>830</x>
      <y>500</y>
      <width>99</width>
      <height>27</height>
     </rect>
    </property>
    <property name="text">
     <string>Analyze</string>
    </property>
   </widget>
   <widget class="QTreeView" name="income_view">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>10</y>
      <width>341</width>
      <height>231</height>
     </rect>
    </property>
   </widget>
   <widget class="QTreeView" name="expenses_view">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>250</y>
      <width>341</width>
      <height>231</height>
     </rect>
    </property>
   </widget>
   <widget class="QTreeView" name="assets_view">
    <property name="geometry">
     <rect>
      <x>10</x>
      <y>490</y>
      <width>341</width>
      <height>361</height>
     </rect>
    </property>
   </widget>
   <widget class="QTreeView" name="liabilities_view">
    <property name="geometry">
     <rect>
      <x>360</x>
      <y>490</y>
      <width>341</width>
      <height>361</height>
     </rect>
    </property>
   </widget>
   <widget class="QTreeView" name="opportunity_view">
    <property name="geometry">
     <rect>
      <x>710</x>
      <y>10</y>
      <width>341</width>
      <height>471</height>
     </rect>
    </property>
   </widget>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>
...