QtextEdit, обновление в реальном времени
Пишу программу, надо что бы окна обновлялись всегда при сканировании RFID метки(ранее использовал Lebel, но не смог реализовать обновление). Начал использовать QtextEdit, ничего не сработало, появилась ошибка
(QObject: Cannot create children for a parent that is in a different thread.
(Parent is QTextDocument(0x1cb56687450), parent's thread is QThread(0x1cb44c95880), current thread is ProgressBarThread(0x1cb56a683c0)
или вообще ничего не обновляется. Подскажите как можно реализовать постоянное обновление данных в QtextEdit с БД.
Вот код: (типо кратко воспроизводимый)
from email.mime import application
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QThread
import sqlite3
import pandas as pd
import json
import sys, time
import numpy as np
from PyQt5.QtGui import QFont
from PyQt5.QtCore import Qt
from PyQt5.QtCore import pyqtSignal
database = './data/testDB.db'
textbase = './data/tags.txt'
DeviceBase = './data/DeviceList.db'
ExcelList = './data/alm_hardware.xlsx'
# database = './data/testDB.db'
# textbase = './data/tags.txt'
# DeviceBase = './data/DeviceList.db'
# ExcelList = './data/alm_hardware.xlsx'
#подключение к базе данных
try:
sqlite_connection = sqlite3.connect(DeviceBase)
cursor = sqlite_connection.cursor()
print("Подключен к SQLite")
except sqlite3.Error as error:
print("Ошибка при работе с SQLite", error)
def insert_varible_into_table(Inventory, Serial, Model, Owner, Location, self): #добавление данных в SQLite
sqlite_insert_with_param = """INSERT INTO DeviceList
(Inv, Serial, Model, Owner, Location)
VALUES (?, ?, ?, ?, ?);"""
data_tuple = (Inventory, Serial, Model, Owner, Location)
cursor.execute(sqlite_insert_with_param, data_tuple)
sqlite_connection.commit()
print("Переменные Python успешно вставлены в таблицу DeviceList")
def LoadDeviseList():
cursor.execute("SELECT * FROM DeviceList")
data = cursor.fetchall()
return data
cursor.execute("SELECT * FROM RFID")
RFID_list = cursor.fetchall()
DeviceList = LoadDeviseList()
def insert_varible_into_table_RFID(Inventory, RFID): #добавление данных в SQLit
if Inventory in str(RFID_list):
cursor.execute("""DELETE FROM RFID WHERE inv = ?""", Inventory)
sqlite_connection.commit()
sqlite_insert_with_param = """INSERT INTO RFID
(Inv, RFID)
VALUES (?, ?);"""
data_tuple = (Inventory, RFID)
cursor.execute(sqlite_insert_with_param, data_tuple)
sqlite_connection.commit()
print("Переменные Python успешно вставлены в таблицу RFID")
def UpdateDevices():
cursor.execute("DELETE FROM DeviceList")
excel_data_df = pd.read_excel(ExcelList, sheet_name='Page 1')
excel_list = json.loads(excel_data_df.to_json(orient='records'))
for item in excel_list:
if str('DECOMISSIONED') != str(item['Fixed Asset Number']):
insert_varible_into_table(item['Fixed Asset Number'], item['Serial number'], item['Display name'], item['Assigned to'], item['Location'])
print('Ready')
def LoadDeviseList():
cursor.execute("SELECT * FROM DeviceList")
data = cursor.fetchall()
return data
class AddNewDevice(QThread):
def __init__(self, mainwindow, parant=None):
super().__init__()
self.mainwindow = mainwindow
inv = self.mainwindow.lineEdit.text()
rfidnum = (self.mainwindow.RFID_Label.text()).partition(';')[0]
insert_varible_into_table_RFID(inv, rfidnum)
test_rfid = ''
class ProgressBarThread(QThread):
def __init__(self, mainwindow, parant=None):
super().__init__()
self.mainwindow = mainwindow
def run(self):
global test_rfid
current_rfid = ''
while True:
self.mainwindow.pushButton_2.setEnabled(True)
with open(textbase) as file:
RFID_original = file.readlines()[-1]
RFID = RFID_original.partition(';')[0]
if current_rfid != RFID:
font = QFont("Arial", 8)
self.mainwindow.RFID_Label.setFont(font)
self.mainwindow.RFID_Label.setText(RFID_original)
if RFID in str(RFID_list):
*res1, = filter(lambda x: x[1] == RFID, RFID_list)
res1 = np.array(res1)
self.mainwindow.Device_Label.setText(f"<html><head/><body><p align=\"center\"><span style=\" font-size:20pt; font-weight:600;\">{str(res1[0][0])}</span></p></body></html>")
current_rfid = RFID
for item in DeviceList:
if str(res1[0][0]) == str(item[0]):
font = QFont("Arial", 18)
self.mainwindow.textEdit.setFont(font)
self.mainwindow.textEdit.setText(str(item[0]))
self.mainwindow.textEdit.setAlignment(Qt.AlignCenter)
self.mainwindow.textEdit_2.setFont(font)
self.mainwindow.textEdit_2.setText(str(item[1]))
self.mainwindow.textEdit_2.setAlignment(Qt.AlignCenter)
self.mainwindow.textEdit_3.setFont(font)
self.mainwindow.textEdit_3.setText(str(item[2]))
self.mainwindow.textEdit_3.setAlignment(Qt.AlignCenter)
self.mainwindow.textEdit_4.setFont(font)
self.mainwindow.textEdit_4.setText(str(item[3]))
self.mainwindow.textEdit_4.setAlignment(Qt.AlignCenter)
self.mainwindow.textEdit_5.setFont(font)
self.mainwindow.textEdit_5.setText(str(item[4]))
self.mainwindow.textEdit_5.setAlignment(Qt.AlignCenter)
application.processEvents()
else:
test_rfid = RFID
self.mainwindow.pushButton_2.setEnabled(True)
self.rfid_detected.emit(RFID) # Emit the detected RFID tag
time.sleep(1)
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.setEnabled(True)
Form.resize(1019, 747)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth())
Form.setSizePolicy(sizePolicy)
Form.setMinimumSize(QtCore.QSize(1019, 747))
Form.setMaximumSize(QtCore.QSize(1019, 747))
font = QtGui.QFont()
font.setPointSize(1)
Form.setFont(font)
Form.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
Form.setStyleSheet("background-color: rgb(134, 134, 134);")
self.pushButton = QtWidgets.QPushButton(Form)
self.pushButton.setEnabled(True)
self.pushButton.setGeometry(QtCore.QRect(350, 530, 281, 61))
font = QtGui.QFont()
font.setFamily("AcadEref")
font.setPointSize(14)
font.setBold(True)
font.setWeight(75)
self.pushButton.setFont(font)
self.pushButton.setStyleSheet("\n"
"border-radius: 20px;\n"
"background-color: rgba(255, 255, 255, 100);")
self.pushButton.setObjectName("pushButton")
self.Device_Label = QtWidgets.QLabel(Form)
self.Device_Label.setGeometry(QtCore.QRect(60, 540, 201, 31))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.Device_Label.setFont(font)
self.Device_Label.setAlignment(QtCore.Qt.AlignCenter)
self.Device_Label.setIndent(-1)
self.Device_Label.setObjectName("Device_Label")
self.RFID_Label = QtWidgets.QLabel(Form)
self.RFID_Label.setGeometry(QtCore.QRect(770, 80, 201, 21))
self.RFID_Label.setAlignment(QtCore.Qt.AlignCenter)
self.RFID_Label.setIndent(-1)
self.RFID_Label.setObjectName("RFID_Label")
self.tableWidget = QtWidgets.QTableWidget(Form)
self.tableWidget.setGeometry(QtCore.QRect(20, 610, 611, 111))
self.tableWidget.setStyleSheet("background-color: rgba(255, 255, 255, 128);")
self.tableWidget.setRowCount(1)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.setColumnCount(5)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(2, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(3, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setHorizontalHeaderItem(4, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(0, 0, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(0, 1, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(0, 2, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(0, 3, item)
item = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(0, 4, item)
self.tableWidget.horizontalHeader().setVisible(True)
self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
self.tableWidget.horizontalHeader().setDefaultSectionSize(120)
self.tableWidget.horizontalHeader().setMinimumSectionSize(20)
self.tableWidget.horizontalHeader().setSortIndicatorShown(True)
self.tableWidget.horizontalHeader().setStretchLastSection(False)
self.tableWidget.verticalHeader().setVisible(False)
self.tableWidget.verticalHeader().setCascadingSectionResizes(False)
self.pushButton_2 = QtWidgets.QPushButton(Form)
self.pushButton_2.setGeometry(QtCore.QRect(780, 130, 180, 70))
font = QtGui.QFont()
font.setFamily("AcadEref")
font.setPointSize(10)
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
self.pushButton_2.setFont(font)
self.pushButton_2.setStyleSheet("border-radius: 20px;\n"
"background-color: rgba(255, 255, 255, 100);")
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_4 = QtWidgets.QPushButton(Form)
self.pushButton_4.setEnabled(True)
self.pushButton_4.setGeometry(QtCore.QRect(780, 250, 180, 70))
font = QtGui.QFont()
font.setFamily("AcadEref")
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.pushButton_4.setFont(font)
self.pushButton_4.setMouseTracking(False)
self.pushButton_4.setStyleSheet("\n"
"border-radius: 20px;\n"
"background-color: rgba(255, 255, 255, 100);")
self.pushButton_4.setObjectName("pushButton_4")
self.lineEdit = QtWidgets.QLineEdit(Form)
self.lineEdit.setGeometry(QtCore.QRect(730, 20, 281, 51))
font = QtGui.QFont()
font.setFamily("AcadEref")
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.lineEdit.setFont(font)
self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)
self.lineEdit.setObjectName("lineEdit")
self.label_2 = QtWidgets.QLabel(Form)
self.label_2.setGeometry(QtCore.QRect(636, 602, 381, 141))
self.label_2.setText("")
self.label_2.setPixmap(QtGui.QPixmap("NESTLE.png"))
self.label_2.setScaledContents(True)
self.label_2.setObjectName("label_2")
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(50, 110, 270, 61))
self.label.setStyleSheet("\n"
"background-color: rgba(255, 255, 255, 0);")
self.label.setObjectName("label")
self.label_4 = QtWidgets.QLabel(Form)
self.label_4.setGeometry(QtCore.QRect(10, 20, 350, 61))
self.label_4.setStyleSheet("\n"
"background-color: rgba(255, 255, 255, 0);")
self.label_4.setObjectName("label_4")
self.label_6 = QtWidgets.QLabel(Form)
self.label_6.setGeometry(QtCore.QRect(60, 200, 250, 61))
self.label_6.setStyleSheet("\n"
"background-color: rgba(255, 255, 255, 0);")
self.label_6.setObjectName("label_6")
self.label_8 = QtWidgets.QLabel(Form)
self.label_8.setGeometry(QtCore.QRect(60, 290, 250, 61))
self.label_8.setStyleSheet("\n"
"background-color: rgba(255, 255, 255, 0);")
self.label_8.setObjectName("label_8")
self.label_9 = QtWidgets.QLabel(Form)
self.label_9.setGeometry(QtCore.QRect(60, 380, 250, 61))
self.label_9.setStyleSheet("\n"
"background-color: rgba(255, 255, 255, 0);")
self.label_9.setObjectName("label_9")
self.label_12 = QtWidgets.QLabel(Form)
self.label_12.setGeometry(QtCore.QRect(6, 2, 711, 471))
self.label_12.setStyleSheet("border-radius: 20px;\n"
"background-color: rgba(255, 255, 255, 100);")
self.label_12.setText("")
self.label_12.setObjectName("label_12")
self.textEdit = QtWidgets.QTextEdit(Form)
self.textEdit.setGeometry(QtCore.QRect(410, 20, 270, 60))
self.textEdit.setMouseTracking(True)
self.textEdit.setFocusPolicy(QtCore.Qt.WheelFocus)
self.textEdit.setStyleSheet("border-radius: 20px;\n"
"background-color: rgba(255, 255, 255, 100);")
self.textEdit.setOverwriteMode(False)
self.textEdit.setAcceptRichText(True)
self.textEdit.setObjectName("textEdit")
self.textEdit_2 = QtWidgets.QTextEdit(Form)
self.textEdit_2.setGeometry(QtCore.QRect(410, 110, 270, 60))
self.textEdit_2.setStyleSheet("border-radius: 20px;\n"
"background-color: rgba(255, 255, 255, 100);")
self.textEdit_2.setObjectName("textEdit_2")
self.textEdit_3 = QtWidgets.QTextEdit(Form)
self.textEdit_3.setGeometry(QtCore.QRect(410, 190, 270, 60))
self.textEdit_3.setStyleSheet("border-radius: 20px;\n"
"background-color: rgba(255, 255, 255, 100);")
self.textEdit_3.setObjectName("textEdit_3")
self.textEdit_4 = QtWidgets.QTextEdit(Form)
self.textEdit_4.setGeometry(QtCore.QRect(410, 280, 270, 60))
self.textEdit_4.setStyleSheet("border-radius: 20px;\n"
"background-color: rgba(255, 255, 255, 100);")
self.textEdit_4.setObjectName("textEdit_4")
self.textEdit_5 = QtWidgets.QTextEdit(Form)
self.textEdit_5.setGeometry(QtCore.QRect(410, 380, 270, 60))
self.textEdit_5.setStyleSheet("border-radius: 20px;\n"
"background-color: rgba(255, 255, 255, 100);")
self.textEdit_5.setObjectName("textEdit_5")
self.label_12.raise_()
self.pushButton.raise_()
self.Device_Label.raise_()
self.RFID_Label.raise_()
self.tableWidget.raise_()
self.pushButton_2.raise_()
self.pushButton_4.raise_()
self.lineEdit.raise_()
self.label_2.raise_()
self.label.raise_()
self.label_4.raise_()
self.label_6.raise_()
self.label_8.raise_()
self.label_9.raise_()
self.textEdit.raise_()
self.textEdit_2.raise_()
self.textEdit_3.raise_()
self.textEdit_4.raise_()
self.textEdit_5.raise_()
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.pushButton.setText(_translate("Form", "Запустить"))
self.Device_Label.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:18pt;\">60010002288</span></p></body></html>"))
self.RFID_Label.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:9pt;\">60010002959</span></p></body></html>"))
item = self.tableWidget.horizontalHeaderItem(0)
item.setText(_translate("Form", "Инвентарный номер"))
item = self.tableWidget.horizontalHeaderItem(1)
item.setText(_translate("Form", "Серийный номер"))
item = self.tableWidget.horizontalHeaderItem(2)
item.setText(_translate("Form", "Модель"))
item = self.tableWidget.horizontalHeaderItem(3)
item.setText(_translate("Form", "Владелец"))
item = self.tableWidget.horizontalHeaderItem(4)
item.setText(_translate("Form", "Расположение"))
__sortingEnabled = self.tableWidget.isSortingEnabled()
self.tableWidget.setSortingEnabled(False)
item = self.tableWidget.item(0, 0)
item.setText(_translate("Form", "60010003856"))
item = self.tableWidget.item(0, 1)
item.setText(_translate("Form", "PF3ETWH7"))
item = self.tableWidget.item(0, 2)
item.setText(_translate("Form", "LENOVO ThinkPad T14 Gen 2 (Intel)"))
item = self.tableWidget.item(0, 3)
item.setText(_translate("Form", "Aleksandr Dorfman ([email protected]) "))
item = self.tableWidget.item(0, 4)
item.setText(_translate("Form", "FACTORY"))
self.tableWidget.setSortingEnabled(__sortingEnabled)
self.pushButton_2.setText(_translate("Form", "Добавить"))
self.pushButton_4.setText(_translate("Form", "Обновить данные"))
self.lineEdit.setText(_translate("Form", "1254672523"))
self.label.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:26pt; font-weight:600;\">Serial number:</span></p></body></html>"))
self.label_4.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:26pt; font-weight:600;\">Inventory number:</span></p></body></html>"))
self.label_6.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:26pt; font-weight:600;\">Model:</span></p></body></html>"))
self.label_8.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:26pt; font-weight:600;\">Owner:</span></p></body></html>"))
self.label_9.setText(_translate("Form", "<html><head/><body><p align=\"center\"><span style=\" font-size:26pt; font-weight:600;\">Location:</span></p></body></html>"))
self.textEdit.setHtml(_translate("Form", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:24pt; font-weight:600;\">60010003030</span></p></body></html>"))
self.textEdit_2.setHtml(_translate("Form", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:24pt; font-weight:600;\">CS2020</span></p></body></html>"))
self.textEdit_3.setHtml(_translate("Form", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:24pt; font-weight:600;\">HP Elitbook</span></p></body></html>"))
self.textEdit_4.setHtml(_translate("Form", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:24pt; font-weight:600;\">Иван Иванович</span></p></body></html>"))
self.textEdit_5.setHtml(_translate("Form", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
"<p align=\"center\" style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:24pt; font-weight:600;\">Sklad</span></p></body></html>"))
def UpdateList():
n = 0
for i in DeviceList:
self.tableWidget.setRowCount(len(DeviceList))
p = 0
for j in i:
self.tableWidget.setItem(n, p, QtWidgets.QTableWidgetItem(str(j)))
p += 1
n += 1
UpdateList()
self.tableWidget.setSortingEnabled(__sortingEnabled)
self.pushButton_2.setText(_translate("Form", "Добавить"))
self.pushButton_4.setText(_translate("Form", "Обновить данные"))
self.pushButton.clicked.connect(self.launch_progress_bar_filling)
self.pushButton_4.clicked.connect(lambda: (UpdateDevices(), UpdateList()))
#self.pushButton_2.clicked.connect(lambda: insert_varible_into_table_RFID(self.lineEdit.text(), (self.RFID_Label.text()).partition(';')[0]))
self.pushButton_2.clicked.connect(lambda: insert_varible_into_table_RFID(self.lineEdit.text(), test_rfid))
self.ProgressbarThread_instance = ProgressBarThread(mainwindow=self)
def launch_progress_bar_filling(self):
self.pushButton.setEnabled(False)
self.ProgressbarThread_instance.start()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
cursor.close()
if sqlite_connection:
sqlite_connection.close()
print("Соединение с SQLite закрыто")
Так еще узнал о каких то сигналах, с помощью этих сигналов можно сделать постоянное обновление данных, но у меня так же не получается это сделать.
Помогите сделать виджет QTextEdit постоянно обновляемым из базы данных, а именно последняя строка или по поиску инвентарника который был сканирован.