-
Notifications
You must be signed in to change notification settings - Fork 581
/
Copy path02_multithreaded.py
49 lines (41 loc) · 1.13 KB
/
02_multithreaded.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from PyQt6.QtCore import *
from PyQt6.QtWidgets import *
from requests import Session
from threading import Thread
from time import sleep
name = input("Please enter your name: ")
chat_url = "https://build-system.fman.io/chat"
server = Session()
# GUI:
app = QApplication([])
text_area = QPlainTextEdit()
text_area.setFocusPolicy(Qt.FocusPolicy.NoFocus)
message = QLineEdit()
layout = QVBoxLayout()
layout.addWidget(text_area)
layout.addWidget(message)
window = QWidget()
window.setLayout(layout)
window.show()
# Event handlers:
new_messages = []
def fetch_new_messages():
while True:
response = server.get(chat_url).text
if response:
new_messages.append(response)
sleep(.5)
thread = Thread(target=fetch_new_messages, daemon=True)
thread.start()
def display_new_messages():
while new_messages:
text_area.appendPlainText(new_messages.pop(0))
def send_message():
server.post(chat_url, {"name": name, "message": message.text()})
message.clear()
# Signals:
message.returnPressed.connect(send_message)
timer = QTimer()
timer.timeout.connect(display_new_messages)
timer.start(1000)
app.exec()