PySide QThread控制来自不同类/ QThread的QWebView

时间:2017-09-28 09:26:08

标签: python python-2.7 pyqt pyside qthread

我看了一遍,看着整个互联网。 我正在尝试在PySide Python中使用QThread,通过单独的线程更改网站/控件JS。在下面的代码中,我尝试在5秒后更改QUrl,重新加载页面。 我需要使用QObjectName吗?如何定位在MainWindow中创建的QWebView。 我做错了什么。

import time
import sys
from PySide.QtCore import *
from PySide.QtGui import *
from PySide.QtWebKit import *

class MainWindow(QMainWindow):

      def __init__(self, parent=None):
          QMainWindow.__init__(self,parent)

          web_window = QWebView()
          #default website at startup
          web_window.load(QUrl("http://www.google.com"))
          web_window.show()

          thread = Thread()
          thread.start()

          sys.exit(app.exec_())


class Thread(QThread):

      def __init__(self):
          QThread.__init__(self)
          print("Thread initialized")

      def run(self):
          print("Thread is running....")

          time.sleep(2) #in 2 seconds open different page
          web_window.load(QUrl("http://www.yahoo.com/"))

          #time.sleep(5) #in 5 seconds open different page
          web_window.load(QUrl("http://www.stackoverflow.com/"))

          #do more thread code here...


if __name__ == '__main__':
    app = QApplication(sys.argv)
    web = MainWindow()

不断收到错误:

  

Traceback(最近一次调用最后一次):文件   “C:\ software \ stackoverflow-sample.py”,第33行,在运行中   web_window.load(QUrl(“http://www.yahoo.com/”))NameError:全局名称   'web_window'未定义

1 个答案:

答案 0 :(得分:0)

全部解决了。 这里有不同的代码 - QThread连接到主GUI(重新加载网站或任何东西)。以下页面非常有帮助:https://nikolak.com/pyqt-threading-tutorial/

import sys, time
from PySide.QtGui import *
from PySide.QtCore import *

class ThreadSignal(QObject):
        sig = Signal(str)

class ThreadMain(QThread):
    def __init__(self, parent = None):
        QThread.__init__(self, parent)
        self.send2thread_signal = ThreadSignal()

    def run(self):
        cc=1
        while (cc > 0):
            cc = cc + 1
            self.send2thread_signal.sig.emit( 'Message #: %s' % cc )

            time.sleep(0.5)

            if (cc == 10):
                print("Time to kill thread")
                cc=-1


class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self,parent)
        print("GUI: Startup & Init")

        self.thread = ThreadMain()
        self.thread.start()
        self.thread.started.connect(self.gui_hello)
        self.thread.finished.connect(self.finished)
        self.thread.send2thread_signal.sig.connect(self.threadcommunication) #thread communication


    def gui_hello(self):
        print("GUI: Thread started." )

    def finished(self):
        print("GUI: Thread finished.")

    def threadcommunication(self,message_from_thread):
        print("GUI: Message from QThread: %s" % message_from_thread )


if __name__=='__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())