2013-06-19 4 views
1

Я новичок в Python и pyQt. Я делаю настольное приложение для какого-то форума. Мое приложение работает правильно, но я не знаю, как я могу разместить мой QWebView элемент на вкладке «QTabWidget»Как разместить QWebView в QTabWidget?

Вот мой полный код:

# -*- 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.menubar = QtGui.QMenuBar() 
     #file = self.menubar.addMenu('Файл') 

     self.tabs = QtGui.QTabWidget() 
     self.tabs.addTab(QtGui.QWidget(),"Темы"); 
     self.tabs.addTab(QtGui.QWidget(),"СМС"); 

     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 Themes(BaseWindow): 
    def __init__(self, parent = None): 
     BaseWindow.__init__(self, parent) 

     self.webview = QWebView() 

     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.webview.page().setLinkDelegationPolicy(QtWebKit.QWebPage.DelegateAllLinks) 
     self.webview.connect(self.webview.page(), QtCore.SIGNAL("linkClicked(const QUrl&)"), self.link_clicked) 

     self.webview.setHtml(html_str) 

     centralLayout = QtGui.QVBoxLayout() 
     centralLayout.addWidget(self.tabs, 1) 
     centralLayout.addWidget(self.webview, 2) 
     self.centralWidget.setLayout(centralLayout) 

     self.setCentralWidget(self.centralWidget) 

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


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

Похоже, что этот enter image description here

Но мне нужно

enter image description here

Спасибо заранее!

ответ

1

У вас есть вам, что вы просили:

centralLayout.addWidget(self.webview, 2) 

вы должны добавить self.webview в расположение внутри вкладки QtGui.QTabWidget.

+0

Вы можете мне помочь? Скажите, пожалуйста, как я могу добавить webview внутри вкладки? Какой метод мне нужен для этого? – Winston

+0

У меня это есть !!! Мне нужно сделать так: 'self.tabs.addTab (self.webview,« Темы »);' Спасибо! – Winston

+1

Замечательно, что вы можете найти точное решение самостоятельно. Вы узнаете больше, чем при принятии заранее подготовленного решения :-) –

Смежные вопросы