我想使用 PyQt5 编写一个包含各种通知消息的应用程序。当用户单击气球消息时,是否可以从气球消息中获取文本?
我编写了一个模拟我的问题的示例代码。每 10 秒发送一次信号的线程。发送信号时,会弹出两种类型的消息。当用户单击消息时tray_msg_clicked
该方法将激活。但这就是我卡住的地方。我无法确定消息是什么。
from PyQt5 import QtCore, QtWidgets
from time import sleep
class Ui_MainWindow(QtWidgets.QMainWindow):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(1218, 502)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QtCore.QSize(827, 500))
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.mythread = ExecuteThread()
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.initUI()
def initUI(self):
self.tray()
self.start_thread()
def start_thread(self):
self.mythread.start()
self.mythread.my_signal.connect(self.thread_signal)
def thread_signal(self, msg):
if msg == "message1":
self.tray_icon.showMessage("Message1", "This is message one.",
QtWidgets.QSystemTrayIcon.Information, 5000)
elif msg == "message2":
self.tray_icon.showMessage("Message2", "This is message two.",
QtWidgets.QSystemTrayIcon.Information, 5000)
def tray_msg_clicked(self):
print("Tray message clicked!")
tray_msg = ""
if tray_msg == "This is message one.":
print("'Message one' code activated.")
# Some code
elif tray_msg == "This is message two.":
print("'Message two' code activated.")
# Some code
def tray(self):
self.tray_icon = QtWidgets.QSystemTrayIcon(self)
self.tray_icon.messageClicked.connect(self.tray_msg_clicked)
self.tray_icon.setIcon(self.style().standardIcon(QtWidgets.QStyle.SP_ComputerIcon))
tray_menu = QtWidgets.QMenu()
self.tray_icon.setContextMenu(tray_menu)
self.tray_icon.show()
class ExecuteThread(QtCore.QThread):
my_signal = QtCore.pyqtSignal(str)
def __init__(self, parent=None):
super(ExecuteThread, self).__init__(parent)
def run(self):
while True:
self.my_signal.emit("message1")
sleep(10)
self.my_signal.emit("message2")
sleep(10)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
有人有任何想法或解决方法来识别这些通知消息中的文本吗?谢谢你的帮助!
负责显示此消息的模块是没有公共接口的QBalloonTip类,因此不幸的是,这在python中不可用。
https://code.woboq.org/qt5/qtbase/src/widgets/util/qsystemtrayicon_p.h.html#QBalloonTip
尝试修改 QSystemTrayIcon 实例的 toolTip 属性,或使用最后一条消息的文本引入一个新变量。