2014-01-07 33 views
2

我正在使用PyQt4創建應用程序,以便能夠在不從系統加載本地HTML文件的情況下查看內嵌文本HTML標記。 但是,我得到了HTML的字符串格式的一些問題。此代碼僅顯示窗口而不是HTML文本。請幫忙。使用QWebView查看內嵌HTML文本()

 

# imported all the modules 

class HtmlView(QtGui.QMainWindow): 
    def __init__(self): 
     QtGui.QMainWindow.__init__(self) 
     ................. 
     # i've skipped the layout definition here 
     ................ 

     # an inline text with html mark-up 

     text = "<p>This is a paragraph</p><div>This is inside div element</div>" 

     self.html = QtWebKit.QWebView() 

     # setting layout 
     self.gridLayout.addWidget(self.html) 
     self.mainLayout.addWidget(self.frame) 
     self.setCentralWidget(self.centralwidget) 

     self.web_page = text 
     url = self.web_page 
     self.html.load(QtCore.QUrl(url)) 
     self.html.show() 

# executing using if __name__ == "main": skipped this part 

並請告訴我怎麼改)元素<p>和<DIV>的QWebView裏面的樣式(。

回答

3

您需要使用setHtml在web視圖加載標記:

self.html = QtWebKit.QWebView() 
    # self.web_page = text 
    # url = self.web_page 
    self.html.setHtml(text) 
    # self.html.show() 

(不需要註釋行)。

樣式的元素,一個樣式表添加到您的標記:

text = """ 
     <html> 
     <style type="text/css"> 
      p {color: red} 
      div {color: blue} 
     </style> 
     <body> 
     <p>This is a paragraph</p> 
     <div>This is inside div element</div> 
     </body> 
     </html> 
    """ 

PS:使用QWebView顯示標記是一個非常重量級的解決方案 - 這可能是更好地使用QTextBrowser,而不是(這是更容易使用)。這隻有一個limited subset of HTML的支持,但它通常是不夠好:

self.html = QtGui.QTextBrowser(self) 
    self.html.setHtml(text) 
+0

再次感謝@ekhumoro ..我在GUI編程是新和PyQt4..so不介意,如果我的問題是愚蠢的......您的解決方案運作良好..感謝:) – dragfire