Здравствуйте. Пытаюсь реализовать интерфейс программы используя Pyside6. Нарисовал форму в QT Designer, создал тестовую базу данных написал небольшой main.py. Не могу понять, как правильно написать код для построчного вывода данных из таблицы в tableWidget. Пытаюсь сделать это при нажатии на кнопку.
Слева в терминале выведены 5 строк с id и названием. Справа в таблицу добавляется только одна строка. Помогите, пожалуйста, разобраться в данной проблеме.
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:secret@localhost: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}'