Guest User

Проблема перезаполнения модели

a guest
Sep 20th, 2013
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.60 KB | None | 0 0
  1. from PySide import QtGui, QtCore
  2. from pymongo import MongoClient
  3.  
  4.  
  5. # тестовая модель
  6. class TableModel(QtCore.QAbstractTableModel):
  7.     def __init__(self, parent):
  8.         super(TableModel, self).__init__(parent)
  9.         # если заполнить модель сразу — отображается нормально, без reset'а
  10.         # self.cursor = mongoclient.sba.products.find() # поиск всех данных
  11.         # но заполним модель в методе updateDataSet, согласно задаче
  12.         self.cursor = None
  13.  
  14.     def updateDataSet(self, lter):
  15.         self.beginResetModel()
  16.         # запрос данных из базы "sba", коллекции "products"
  17.         self.cursor = mongoclient.sba.products.find(lter)
  18.         self.endResetModel()
  19.  
  20.     def __data__(self, index, role):
  21.         if not index.isValid():
  22.             return None
  23.  
  24.         if index.row() > self.cursor.count():
  25.             return None
  26.  
  27.         if role != QtCore.Qt.QDisplayRole:
  28.             return None
  29.  
  30.         try:
  31.             # итерация по курсору, при завершении выбрасывает исключение StopIteration
  32.             row = self.cursor.__next__()
  33.         except StopIteration as e:
  34.             return None
  35.  
  36.         if index.column() == 0:
  37.             return row['code']
  38.         elif index.column() == 1:
  39.             return row['title']
  40.  
  41.     def rowCount(self, parent=None):
  42.         if not self.cursor:
  43.             return 0
  44.         return self.cursor.count()
  45.  
  46.     def columnCount(self, parent=None):
  47.         return 2
  48.  
  49.     def headerData(self, section, orientation, role):
  50.         if role != QtCore.Qt.DisplayRole:
  51.             return None
  52.  
  53.         if orientation == QtCore.Qt.Horizontal:
  54.             if section == 0:
  55.                 return 'Код'
  56.             elif section == 1:
  57.                 return 'Наименование'
  58.  
  59.         return None
  60.  
  61. if __name__ == '__main__':
  62.     app = QtGui.QApplication([])
  63.     # клиент
  64.     mongoclient = MongoClient()
  65.  
  66.     # окно
  67.     widget = QtGui.QWidget()
  68.     layout = QtGui.QVBoxLayout(widget)
  69.  
  70.     # модель и представление
  71.     tableView = QtGui.QTableView(widget)
  72.     tableModel = TableModel(tableView)
  73.     tableView.setModel(tableModel)
  74.     layout.addWidget(tableView)
  75.  
  76.     # кнопки внизу окна
  77.     hbox = QtGui.QHBoxLayout()
  78.     layout.addLayout(hbox)
  79.     hbox.addStretch()
  80.  
  81.     loadAllButton = QtGui.QPushButton('Загрузить всё', widget)
  82.     loadAllButton.clicked.connect(lambda: tableModel.updateDataSet(None))
  83.     hbox.addWidget(loadAllButton)
  84.  
  85.     loadLterButton = QtGui.QPushButton('Условный фильтр', widget)
  86.     loadLterButton.clicked.connect(lambda: tableModel.updateDataSet({'prices.price' : {'$gt' : 3000}}))
  87.     hbox.addWidget(loadLterButton)
  88.  
  89.     # шоу и выход
  90.     widget.show()
  91.     exit(app.exec_())
Advertisement
Add Comment
Please, Sign In to add comment