Как сделать обновление comboBox, при добавлении данных в бд
У меня есть 2 окна, 1-ое главное, из него запускается второе.
Второе окно используется для добавления данных в бд, и последующий вывод на первом окне, на первом окне есть comboBox с метками, которые берутся из бд.
Мне нужно, чтобы когда пользователь запускает 2 окно, вводит данные, и нажимает Ok, чтобы comboBox на первой странице обновлялся с новыми данными.
Как это можно сделать? Привожу ниже код 1 и 2 окна без ненужных вещей (считайте что база данных есть).
1-ое окно:
import sys
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow
from add_receipt import add_receipt
import sqlite3
class Recepts(QMainWindow):
def __init__(self):
super().__init__()
uic.loadUi('recepts.ui', self)
self.add_receipt = add_receipt()
def call_add_receipt(self):
self.add_receipt.show()
while not self.add_receipt.added_new_recept:
pass
self.update()
2-е окно:
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtWidgets import QWidget, QApplication
import sys
import sqlite3
class add_receipt(QWidget):
def __init__(self):
super(add_receipt, self).__init__()
uic.loadUi('new_recept.ui', self)
def accepted(self):
if self.lineEdit.text().strip() == '':
self.lineEdit.setStyleSheet('border: 1px solid red')
elif self.plainTextEdit.toPlainText().strip() == '':
self.plainTextEdit.setStyleSheet('border: 1px solid red')
elif self.lineEdit_2.text().strip() == '':
self.lineEdit_2.setStyleSheet('border: 1px solid red')
else:
self.cursor.execute("""INSERT INTO
recepts(title, description, marks) VALUES(?, ?, ?)""",
(self.lineEdit.text(), self.plainTextEdit.toPlainText().replace("\n",
"\t"),
' '.join(self.lineEdit_2.text().split())))
self.lineEdit_2.clear()
self.lineEdit.clear()
self.plainTextEdit.clear()
self.added_new_recept = True
self.close()
Это 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>353</width>
<height>458</height>
</rect>
</property>
<property name="windowTitle">
<string>Книга рецептов</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QComboBox" name="comboBox">
<property name="geometry">
<rect>
<x>60</x>
<y>130</y>
<width>191</width>
<height>22</height>
</rect>
</property>
</widget>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>353</width>
<height>21</height>
</rect>
</property>
<widget class="QMenu" name="menu">
<property name="title">
<string>Возможности</string>
</property>
<addaction name="action"/>
</widget>
<addaction name="menu"/>
</widget>
<widget class="QStatusBar" name="statusbar"/>
<action name="action">
<property name="text">
<string>Добавить рецепт</string>
</property>
</action>
</widget>
<resources/>
<connections/>
</ui>
Это ui второго окна:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>615</width>
<height>495</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<widget class="QWidget" name="verticalLayoutWidget">
<property name="geometry">
<rect>
<x>29</x>
<y>22</y>
<width>561</width>
<height>431</height>
</rect>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<property name="spacing">
<number>20</number>
</property>
<item>
<layout class="QHBoxLayout" name="horizontalLayout_3">
<item>
<widget class="QLabel" name="label_3">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="minimumSize">
<size>
<width>120</width>
<height>0</height>
</size>
</property>
<property name="font">
<font>
<pointsize>10</pointsize>
</font>
</property>
<property name="text">
<string>Метки(записывать через пробел без запятых):</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="lineEdit_2"/>
</item>
</layout>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
<resources/>
<connections/>
</ui>
*Я сократил всё, и оставил только то что не понимаю
Ответы (1 шт):
Автор решения: S. Nick
→ Ссылка
Примерно так:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets, uic
from PyQt5.QtWidgets import QWidget, QApplication, QMainWindow
import sqlite3
#from add_receipt import AddReceipt # - add_receipt, + AddReceipt
class AddReceipt(QtWidgets.QDialog): # - QWidget, + QDialog
def __init__(self):
super(AddReceipt, self).__init__()
uic.loadUi('new_recept.ui', self)
'''
def accepted(self):
if self.lineEdit.text().strip() == '':
self.lineEdit.setStyleSheet('border: 1px solid red')
elif self.plainTextEdit.toPlainText().strip() == '':
self.plainTextEdit.setStyleSheet('border: 1px solid red')
elif self.lineEdit_2.text().strip() == '':
self.lineEdit_2.setStyleSheet('border: 1px solid red')
else:
self.cursor.execute("""INSERT INTO
recepts(title, description, marks) VALUES(?, ?, ?)""",
(self.lineEdit.text(), self.plainTextEdit.toPlainText().replace("\n",
"\t"),
' '.join(self.lineEdit_2.text().split())))
self.lineEdit_2.clear()
self.lineEdit.clear()
self.plainTextEdit.clear()
self.added_new_recept = True
self.close()
'''
class Recepts(QMainWindow):
def __init__(self):
super().__init__()
uic.loadUi('recepts.ui', self)
self.menu.triggered.connect(self.call_add_receipt) # +++
self.add_receipt = AddReceipt()
self.add_receipt.buttonBox.accepted.connect(self._accepted) # +++
self.add_receipt.buttonBox.rejected.connect(self.add_receipt.reject) # +++
def call_add_receipt(self): # +++
self.add_receipt.exec_() # - show(), + exec_()
def _accepted(self): # +++
if not self.add_receipt.lineEdit_2.text():
msg = QtWidgets.QMessageBox.information(self, 'Message',
'Введите <b>Метки</b> или нажмите <b>Cancel</b>.')
return
_list = self.add_receipt.lineEdit_2.text().split() # - strip(), + split()
self.comboBox.clear()
self.comboBox.addItems(_list)
self.add_receipt.hide()
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = Recepts()
w.show()
sys.exit(app.exec_())
