1

我是 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_())

运行后是这样的

在此处输入图像描述

我有问题。此代码在显示“QMainWINdow”窗口之前从网站加载数据。但我只需要在窗口显示之后加载数据。有没有办法我可以做到这一点?

例如在 JavaScript 中

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

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

提前致谢!

4

1 回答 1

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)
于 2013-06-20T20:43:28.077 回答