M
M
ma-r_k-us2021-05-16 22:19:41
Python
ma-r_k-us, 2021-05-16 22:19:41

How to display records from database in tableWidget using Pyside6/QT6?

Hello. I'm trying to implement a program interface using Pyside6. I drew a form in QT Designer, created a test database and wrote a small main.py. I can't figure out how to write the code for line-by-line output of data from a table to tableWidget. I'm trying to do it on button click. 60a16f09dc7cd796492935.png
On the left side of the terminal there are 5 lines with id and title. On the right, only one row is added to the table. Help, please, to understand this problem.

main.py

import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QTableWidgetItem
from new__form import Ui_MainWindow

from db import Author
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

Base = declarative_base()

engine = create_engine('postgresql://postgres:[email protected]:5432/stage')
session_factory = sessionmaker(bind=engine)
Session = scoped_session(session_factory)
Base.metadata.create_all(engine)

class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.pushButton_2.clicked.connect(self.buttonClicked)

def buttonClicked(self):
session = Session()
for author in session.query(Author).order_by(Author.author_id):
print(author.author_id, author.name)
for row in range(10):
for col in range(2):
self.ui.tableWidget.setItem(
row, col, QTableWidgetItem(f"({author.author_id},{author.name})")
)

if __name__ == "__main__":
app = QApplication()

window = MainWindow()
window.show()

sys.exit(app.exec_())


new_form.py

# -*- coding: utf-8 -*-

################################################################################
## Form generated from reading UI file 'new_form.ui'
##
## Created by: Qt User Interface Compiler version 6.0.4
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
################################################################################

from PySide6.QtCore import *
from PySide6.QtGui import *
from PySide6.QtWidgets import *

class Ui_MainWindow(object):
def setupUi(self, MainWindow):
if not MainWindow.objectName():
MainWindow.setObjectName(u"MainWindow")
MainWindow.resize(640, 480)
self.centralwidget = QWidget(MainWindow)
self.centralwidget.setObjectName(u"centralwidget")
self.tabWidget = QTabWidget(self.centralwidget)
self.tabWidget.setObjectName(u"tabWidget")
self.tabWidget.setGeometry(QRect(0, 0, 631, 291))
self.tab_posetiteli = QWidget()
self.tab_posetiteli.setObjectName(u"tab_posetiteli")
self.tableWidget = QTableWidget(self.tab_posetiteli)
if (self.tableWidget.columnCount() < 2):
self.tableWidget.setColumnCount(2)
__qtablewidgetitem = QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(0, __qtablewidgetitem)
__qtablewidgetitem1 = QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(1, __qtablewidgetitem1)
if (self.tableWidget.rowCount() < 1):
self.tableWidget.setRowCount(1)
__qtablewidgetitem2 = QTableWidgetItem()
self.tableWidget.setVerticalHeaderItem(0, __qtablewidgetitem2)
__qtablewidgetitem3 = QTableWidgetItem()
self.tableWidget.setItem(0, 0, __qtablewidgetitem3)
__qtablewidgetitem4 = QTableWidgetItem()
self.tableWidget.setItem(0, 1, __qtablewidgetitem4)
self.tableWidget.setObjectName(u"tableWidget")
self.tableWidget.setGeometry(QRect(30, 10, 256, 192))
self.pushButton = QPushButton(self.tab_posetiteli)
self.pushButton.setObjectName(u"pushButton")
self.pushButton.setGeometry(QRect(30, 210, 94, 28))
self.pushButton_2 = QPushButton(self.tab_posetiteli)
self.pushButton_2.setObjectName(u"pushButton_2")
self.pushButton_2.setGeometry(QRect(190, 210, 94, 28))
self.tabWidget.addTab(self.tab_posetiteli, "")
self.tab_prodaza = QWidget()
self.tab_prodaza.setObjectName(u"tab_prodaza")
self.tabWidget.addTab(self.tab_prodaza, "")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QMenuBar(MainWindow)
self.menubar.setObjectName(u"menubar")
self.menubar.setGeometry(QRect(0, 0, 640, 30))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QStatusBar(MainWindow)
self.statusbar.setObjectName(u"statusbar")
MainWindow.setStatusBar(self.statusbar)

self.retranslateUi(MainWindow)

self.tabWidget.setCurrentIndex(0)

QMetaObject.connectSlotsByName(MainWindow)
# setupUi

def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", u"MainWindow", None))
___qtablewidgetitem = self.tableWidget.horizontalHeaderItem(0)
___qtablewidgetitem.setText(QCoreApplication.translate("MainWindow", u"id", None));
___qtablewidgetitem1 = self.tableWidget.horizontalHeaderItem(1)
___qtablewidgetitem1.setText(QCoreApplication.translate("MainWindow", u"FIO", None));
___qtablewidgetitem2 = self.tableWidget.verticalHeaderItem(0)
___qtablewidgetitem2.setText(QCoreApplication.translate("MainWindow", u"test", None));

__sortingEnabled = self.tableWidget.isSortingEnabled()
self.tableWidget.setSortingEnabled(False)
___qtablewidgetitem3 = self.tableWidget.item(0, 0)
___qtablewidgetitem3.setText(QCoreApplication.translate("MainWindow", u"1", None));
___qtablewidgetitem4 = self.tableWidget.item(0, 1)
___qtablewidgetitem4.setText(QCoreApplication.translate("MainWindow", u"Test Tesov", None));
self.tableWidget.setSortingEnabled(__sortingEnabled)

self.pushButton.setText(QCoreApplication.translate("MainWindow", u"Read", None))
self.pushButton_2.setText(QCoreApplication.translate("MainWindow", u"Add", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_posetiteli), QCoreApplication.translate("MainWindow", u"Posetiteli", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_prodaza), QCoreApplication.translate("MainWindow", u"Prodaza", None))
# retranslateUi


db

from sqlalchemy import Column, ForeignKey, Integer, String, Text, Date, DateTime
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Topic(Base):
__tablename__ = 'topic'
__tableargs__ = {
'comment': 'Темы цитат'
}

topic_id = Column(
Integer,
nullable=False,
unique=True,
primary_key=True,
autoincrement=True
)
name = Column(String(128), comment='Наименование темы')
description = Column(Text, comment='Описание темы')

def __repr__(self):
return f'{self.topic_id} {self.name} {self.description}'

class Author(Base):

__tablename__ = 'author'
__tableargs__ = {
'comment': 'Авторы цитат'
}

author_id = Column(
Integer,
nullable=False,
unique=True,
primary_key=True,
autoincrement=True
)
name = Column(String(128), comment='Имя автора')
birth_date = Column(Date, comment='Дата рождения автора')
country = Column(String(128), comment='Страна рождения автора')

def __repr__(self):
return f'{self.author_id} {self.name} {self.birth_date} {self.country}'

class Quote(Base):

__tablename__ = 'quote'
__tableargs__ = {
'comment': 'Цитаты'
}

quote_id = Column(
Integer,
nullable=False,
unique=True,
primary_key=True,
autoincrement=True
)
text = Column(Text, comment='Текст цитаты')
created_at = Column(DateTime, comment='Дата и время создания цитаты')
author_id = Column(Integer, ForeignKey('author.author_id'), comment='Автор цитаты')
topic_id = Column(Integer, ForeignKey('topic.topic_id'), comment='Тема цитаты')
author = relationship('Author', backref='quote_author', lazy='subquery')
topic = relationship('Topic', backref='quote_topic', lazy='subquery')

def __repr__(self):
return f'{self.text} {self.created_at} {self.author_id} {self.topic_id}'

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
ma-r_k-us, 2021-05-17
@ma-r_k-us

Thank you. In general, the functionality is not great: gui --> pyside6, orm --> sqlalchemy.
PS suddenly someone come in handy. Decision:

def buttonClicked(self):
    session = Session()
    authors = session.query(Author).order_by(Author.author_id)

    for author in authors:
        print(author.author_id, author.name)

        row = self.ui.tableWidget.rowCount()
        self.ui.tableWidget.insertRow(row)

        self.ui.tableWidget.setItem(row, 0, QTableWidgetItem(f"{author.author_id}")
        self.ui.tableWidget.setItem(row, 1, QTableWidgetItem(f"{author.name}")

P
Pixilys, 2021-05-17
@Pixilys

Here is a good example
https://is20-2019.susu.ru/utkinaea/2021/03/15/obra... In
general, try to simplify the task, and then supplement with different functionality.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question