K
K
kamilm2019-09-16 19:02:33
Python
kamilm, 2019-09-16 19:02:33

I can't access a function from another thread. What should I do?

I have a class Ui_Dialog which has a QTextEdit,
there is a function that includes a thread with a bot

self.Bot_Thread_instance = Bot_Thread(mainwindow=self)
self.On.clicked.connect(self.launch)
def launch(self):
    self.Bot_Thread_instance.start()

in the code below, the bot function in another thread, in the class Bot_Thread(QtCore.QThread)
def run(self):
   Bot = vk.ChatBot(token = '', version_API = 5.101, group_id = '')
   Server = Bot.Auth()
   LongPoll = Bot.Listen()
   person = Bot.GetUserInfo()
   Server['ts'] = LongPoll['ts']
   while True:
        LongPoll = Bot.Listen()
        updates = LongPoll['updates']
        if updates: 
            for element in updates:
                action_code = element[0]
                if action_code == 4:
                    summands = []  
                    flag = element[2]
                    for number in [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 65536]:  
                        if flag & number:  
                            summands.append(number)
                    if 2 not in summands:
                        timestamp = element[4]
                        value = datetime.datetime.fromtimestamp(timestamp)
                        log = 'Сообщение от пользователя: %s\nid пользователя: %s\nДата отправки: %s\n' %(element[6], element[3], value.strftime("%Y-%m-%d %H.%M.%S"))
                        ui.Log.setText(log)
        Server['ts'] = LongPoll['ts']

I need the log to be displayed in a QTextEdit which is on a different thread, in the Ui_Dialog class.
just in case ui = Ui_Dialog()
Error
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QTextDocument(0x13402b01610), parent's thread is QThread(0x13402b00690), current thread is Bot_Thread(0x13402b02030)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tsarevfs, 2019-09-16
@kamilm

C UI in Qt can only work from one thread. To communicate safely with UI from other threads, use signals.
https://stackoverflow.com/a/638693/1762922

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question