如何启动http连接,只有在窗口显示后?

时间:2013-06-20 20:17:42

标签: python python-3.x pyqt4

我是python&的新手PyQt的

这是我的代码

# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui, QtWebKit
from PyQt4.QtWebKit import QWebView
import http.client as http_c
import sys, os, webbrowser #re, html5lib

import lxml.html
from lxml import etree

class BaseWindow(QtGui.QMainWindow):
    def __init__(self, parent = None):
        QtGui.QMainWindow.__init__(self, parent)
        self.centralWidget = QtGui.QWidget()
        self.resize(800, 500)
        self.setWindowTitle('PHP-Forum.ru')

        self.tabs = QtGui.QTabWidget()
        # self.tabs.addTab(QtGui.QWidget(),"Themes");

        exit = QtGui.QAction(QtGui.QIcon('icons/exit.png'), 'Выход', self)
        exit.setShortcut('Ctrl+Q')
        self.connect(exit, QtCore.SIGNAL('triggered()'), QtCore.SLOT('close()'))

        menubar = self.menuBar()
        file = menubar.addMenu('Файл')
        file.addAction(exit)

        settings = menubar.addMenu('Установки')

class Loader(BaseWindow):
    loaded_themes = False
    def __init__(self, parent = None):
        BaseWindow.__init__(self, parent)

        self.webview = QWebView()

        self.webview.page().setLinkDelegationPolicy(QtWebKit.QWebPage.DelegateAllLinks)
        self.webview.connect(self.webview.page(), QtCore.SIGNAL("linkClicked(const QUrl&)"), self.link_clicked)

        #self.sbar = QtGui.QStatusBar(self)
        #self.sbar.showMessage('Ready')
        #self.setStatusBar(self.sbar)

        if not self.loaded_themes:
            self.load_themes()
            self.webview.setHtml(self.html_str)

        centralLayout = QtGui.QVBoxLayout()
        centralLayout.addWidget(self.tabs, 1)
        self.tabs.addTab(self.webview, "Themes");
        self.tabs.addTab(QtGui.QWidget(),"SMS");

        self.centralWidget.setLayout(centralLayout)
        self.setCentralWidget(self.centralWidget)

    def load_themes(self):
        con = http_c.HTTPConnection('phpforum.ru')
        con.request('GET', '/ssi.php?a=news&show=25')
        res = con.getresponse()
        html_code = res.read().decode('cp1251')

        path = os.getcwd()
        rpath = os.path.normpath(path + '/resources/').replace('\\', '/')
        self.setWindowIcon(QtGui.QIcon(rpath + '/images/favicon.ico'))

        doc = lxml.html.document_fromstring(html_code)
        topics = doc.xpath('/html/body/table[@class="topic"]')

        data = []
        i = 0
        for topic in topics:
            i += 1
            t_str = lxml.html.document_fromstring(etree.tostring(topic))
            author_name = t_str.xpath('//a[@class="author"]/text()')
            author_link = t_str.xpath('//a[@class="author"]/@href')
            last_post = t_str.xpath('//span[@class="post_date"]/text()[1]')
            title = t_str.xpath('//span[@class="topic_title"]/text()')
            topic_link = t_str.xpath('//a[@class="topic_link"]/@href')
            topic_text = t_str.xpath('//table[1]//tr[3]/td/text()')

            try:
                author_name = author_name[0]
            except IndexError:
                author_name = 'Guest'
                author_link = '#'
            else:
                author_link = author_link[0]

            try:
                topic_text = topic_text[0]
            except IndexError:
                topic_text = None

            data.append({
                'title': title[0],
                'author_name': author_name,
                'author_link': author_link,
                'last_post': last_post[0],
                'topic_link': topic_link[0],
                'topic_text': topic_text,
            })

        html_str = """
            <!DOCTYPE html>
            <html>
            <head>
                <link rel="stylesheet" type="text/css" href="C:/Python33/scripts/pqt/phpforum/resources/css/style.css">
            </head>
            <body>
        """
        for info in data:
            html_str += """
            <div class="topic">
                <span class="title"><a href="{topic_link}">{title}</a></span>
                <span class="author"><a href="{author_link}">{author_name}</a></span>
                <span class="time">{last_post}</span>
            </div>
            <br>
            """.format(**info)

        html_str += """
            </body>
            </html>
        """
        self.html_str = html_str

    def link_clicked(self, url):
        webbrowser.open(str(url.toString()))


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

运行后看起来像这样

enter image description here

我有问题。此代码在显示“QMainWIndow”窗口之前加载来自网站的数据。但我只需要在窗口显示后加载数据。 有什么方法可以做到吗?

例如在JavaScript中

document.onload = function(){
    //This Code will be executed only after HTML page will be loaded
}

我需要在显示窗口之后开始加载数据。可能是pyQt中的任何“SIGNALS”吗?

提前致谢!

1 个答案:

答案 0 :(得分:0)

由于这篇文章https://stackoverflow.com/a/10677566/813069

,我的问题已经解决了

Loader.__init__()我添加了

QtCore.QTimer.singleShot(500, self.OnLoadThemes)

我还在Loader

添加了一种方法
def OnLoadThemes(self):
    self.load_themes()
    self.webview.setHtml(self.html_str)