为什么PyQt4插槽收到一个信号多个tim

2024-09-28 23:18:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用pyuic4创建GUI并创建一个线程,当该线程完成时,它将结果附加到textbrowser。 问题是: 当我在“主机或URL”中输入一些文本时,点击“Do check”按钮,它会打印出“this is text”一次。但以后每次修改时,我都会按两次“打印”按钮。日志上说信号只发射一次,而插槽函数被调用了很多次。我不知道我错过了什么。有人能提出解决办法吗? 谢谢你能提供的任何帮助

这是我的主.py在

import logging
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QMessageBox
from form1 import *

logging.basicConfig(filename="netchecker.log", filemode='w',\
        format='%(asctime)s %(levelname)s %(message)s',
        level=logging.DEBUG)

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

class PingThread(QtCore.QThread):
    def run(self):
        logging.debug("*****Done pingThread")
        all_res = "this is text"
        self.emit(QtCore.SIGNAL("Data"), all_res)

class MyApp(Ui_MainWindow):
    def __init__(self, app):
        logging.info("Init MyAPP")
        self.app = app
        self.pingThread = PingThread()

    def setupUi(self, *args):
        super(MyApp, self).setupUi(*args)
        logging.info("setupUi")
        QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.doCheck)

    def append_to_text_browser(self, newtext):
        """This method is callback for some thread run separated
        from main thread"""
        logging.debug("Inside append_to_text_browser")
        self.textBrowser.append(newtext)
        self.app.processEvents()

    def onNewUrl(self):
        font = QtGui.QFont()
        self.pushButton.setFont(font)
        del font
        self.pushButton.setText(QtGui.QApplication.translate("MainWindow", "Do new check", None, QtGui.QApplication.UnicodeUTF8))
        self.pushButton.setEnabled(True)
        self.app.processEvents()

    def doCheck(self):
        logging.info("doCheck beginning")
        self.textBrowser.clear()
        QtCore.QObject.connect(self.pingThread, \
                QtCore.SIGNAL("Data"), \
                self.append_to_text_browser)
        logging.info("Called pingThread")
        self.pingThread.start()

if __name__ == "__main__":

    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    MainWindow.setWindowIcon(QtGui.QIcon('zChecker.png'))
    ui = MyApp(app)

    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

以及由pyuic4 form1.py转换的文件:

^{pr2}$

Tags: textfromimportselfinfoapploggingdef