马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
from PyQt6 import uic
from PyQt6.QtWidgets import QApplication, QMainWindow
import sys
with open("users", "w") as f:
pass
form_class = uic.loadUiType("ThisChat.ui")[0]
class ThisChat(QMainWindow, form_class):
def __init__(self):
super().__init__()
self.setupUi(self)
self.set1 = [
self.label1,
self.label2,
self.now,
self.sendmsg,
self.tb,
self.name,
self.users
]
self.set2 = [
self.label3,
self.uncf,
self.un
]
for each in self.set1:
each.setVisible(False)
self.sendmsg.clicked.connect(self.send)
self.uncf.clicked.connect(self.confirmUsername)
self.username = None
def send(self):
if self.username is None:
return
text = self.now.text()
self.tb.append(f"{self.username}:\n{text}")
def confirmUsername(self):
username = self.un.text().strip()
if username == '':
return
for each in self.set1:
each.setVisible(True)
for each in self.set2:
each.setVisible(False)
self.username = username
self.name.setText(username)
self.add_user(username)
def add_user(self, username):
users = self.get_users()
with open("users", "w") as f:
users.append(username.rstrip("\n") + "\n")
f.writelines(users)
def get_users(self):
with open("users", "r") as f:
users = f.readlines()
return users
if __name__ == "__main__":
app = QApplication(sys.argv)
myapp = ThisChat()
myapp.show()
sys.exit(app.exec())
现在我希望创建一个定时器,每隔 1 秒调用get_users方法
您可以使用PyQt6的QTimer类来创建定时器,并将其连接到get_users方法。在构造函数中添加以下代码:from PyQt6.QtCore import QTimerclass ThisChat(QMainWindow, form_class): def __init__(self): super().__init__() self.setupUi(self) # 其他代码... self.timer = QTimer(self) # 创建定时器 self.timer.timeout.connect(self.get_users) # 将定时器的timeout信号连接到get_users方法 self.timer.start(1000) # 每隔1秒触发一次定时器 # 其他方法...
这样,每隔1秒钟,定时器将触发一次timeout信号,然后调用get_users方法。请注意,get_users方法中的代码可能需要进行一些修改,以便在更新用户列表时进行适当的操作。
希望这可以帮助到您!
|