Добавление текста в QTextEdit из другого класса

Рейтинг: 1Ответов: 1Опубликовано: 28.05.2023

Создаю чат-клиент на PyQt5. Я пытаюсь добавить из другого класса в text_field (объект класса QTextEdit) текст получаемого сообщения. Каким образом можно это реализовать в моём коде?

#python 3.11.1
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QVBoxLayout, QSplitter, QPushButton, QDialog, QRadioButton, QLabel, QLineEdit,QListWidget
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
from PyQt6.QtCore import QThread
from PyQt6.QtCore import QTimer
from PyQt5 import QtGui
from threading import Thread as thd
from PyQt6.QtCore import QThread, pyqtSignal
import time


class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.count_of_buttons = 0
        # создаем три макета
        layout1 = QHBoxLayout()
        layout2 = QVBoxLayout()
        layout3 = QVBoxLayout
        self.text_field = QTextEdit(self)
        
        # задаем размер текстового поля
        self.text_field.setFixedSize(200, 500)  
        
        layout2.addWidget(self.text_field)
        
        dlg.setLayout(layout)
        dlg.exec_()
        
class WorkerThread(QThread):
    finished = pyqtSignal() # сигнал, который будет отправлен после выполнения

    def __init__(self, parent=None):
        super().__init__(parent)

    def run(self):
        text_field.append("Добавленный текст")
        time.sleep(5)
        self.finished.emit()
        

app = QApplication(sys.argv)
worker = WorkerThread()
worker.start()
window = Window()
window.show()
sys.exit(app.exec_())

Ответы

▲ 3Принят

Можно сделать так:

#python 3.11.1
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QVBoxLayout, QSplitter, QPushButton, QDialog, QRadioButton, QLabel, QLineEdit,QListWidget
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5 import QtCore
from PyQt6.QtCore import QThread
from PyQt6.QtCore import QTimer
from PyQt5 import QtGui
from threading import Thread as thd
from PyQt6.QtCore import QThread, pyqtSignal
import time

# эта строка нужна для того, чтобы потом присвоить этой переменной значение
text_field = None


class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.count_of_buttons = 0
        # создаем три макета
        layout1 = QHBoxLayout()
        layout2 = QVBoxLayout()
        layout3 = QVBoxLayout
        
        # global нужен для того, чтобы вынести переменную в глобальную область видимости
        global text_field
        # а дальше всё как обычно
        text_field = QTextEdit(self)
        
        # задаем размер текстового поля
        text_field.setFixedSize(200, 500)  
        
        layout2.addWidget(text_field)
        
        self.dlg.setLayout(layout)
        self.dlg.exec_()
        
class WorkerThread(QThread):
    finished = pyqtSignal() # сигнал, который будет отправлен после выполнения

    def __init__(self, parent=None):
        super().__init__(parent)

    def run(self):
        # тут можно делать что угодно с text_field
        text_field.append("Добавленный текст")
        time.sleep(5)
        self.finished.emit()
        
app = QApplication(sys.argv)
# Window нужно обязательно нужно инициализировать до WorkerThread, иначе будет говорить, что text_field равняется None
window = Window()

# А дальше всё как обычно
worker = WorkerThread()
worker.start()
window.show()
sys.exit(app.exec_())

Рядом с теми строками, которые я изменил, я добавил комментарии.