0

I have a sqllite data table created with sqlalchemy that i would like to represent on a PyQt5 tablewidget.

    def createTable(self, tableData):
      self.qTable = session.query(tableData).all()
      self.tableWidget = QTableWidget()
      self.tableWidget.setRowCount(0)
      self.tableWidget.setColumnCount(tableData.cols)
      self.tableWidget.setHorizontalHeaderLabels(tableData.col_headers)
      for row, form in enumerate(self.qTable):
        self.tableWidget.setRowCount(row+1)
           for col,record in enumerate(form):
                self.tableWidget.setItem(row, col, QTableWidgetItem(record))

This breaks at the line

for col,record in enumerate(form):

with an error "TypeError: 'Tests' object is not iterable"

The ORM is built with this code

class Tests(Base):
  __tablename__ = 'tests'
  id = Column(Integer, primary_key=True)
  current = Column(Boolean)
  temp = Column(Float)
  brine = Column (Float)
  test = Column(String)
  pc = Column(Float)
  wait_time = Column(Integer)
  headers = {"current","temp","brine","test","pc","wait time"}

is there a way to make this iterable? or a neater way of dealing with this??

  • Have a look at the `keyvalgen()` function I’ve written in [this answer](https://stackoverflow.com/a/54034230/6560549). It produces tuples of format `attrib name, value` and ignores the private SQLalchemy attributes. – SuperShoot Feb 13 '19 at 20:38
  • perfect thanks @SuperShoot – Ian Mangelsdorf Feb 14 '19 at 10:45

1 Answers1

0

Thanks @SuperShoot, this worked pretty well for me here is the final code I used

 for row, form in enumerate(self.qTable):
        col = 0
        self.tableWidget.setRowCount(row+1)
        for c in columns:
            for k,v in vars(form).items():
                if k == c:
                    self.tableWidget.setItem(row, col, QTableWidgetItem(str(v)))
                    col +=1

I added extra logic so i can define the column order,

  • Instead of managing the `col` counter variable yourself you can use `for col, c in enumerate(columns):`. – SuperShoot Feb 15 '19 at 05:19