Search code examples
pythontabspyqtpyqt4qwebview

Python PyQt QWebView load site in clicked tab


I need your help!

The situation: I have different tabs and in one tab ["Support"-Tab] I want to use the QWebView Widget. But the site should first load when I click on this tab:

main.py

import sys
from PyQt4 import QtCore, QtGui, QtWebKit
from tab-file import Support

class Widget(QtGui.QWidget):

    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        self.createTabs()

        widgetLayout = QtGui.QVBoxLayout()
        widgetLayout.addWidget(self.tabs)
        self.setLayout(widgetLayout)

        self.setWindowTitle("Tabs")
        self.resize(400,400)


    def createTabs(self):
        self.tabs = QtGui.QTabWidget()

        support = Support()

        tab1 = QtGui.QWidget()
        tab2 = support

        self.tabs.addTab(tab1,"tab1")
        self.tabs.addTab(tab2,"SUPPORT")

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

I load the "Support"-Tab from this file:

tab-file.py

import sys
from PyQt4 import QtGui, QtCore, QtWebKit


class Support(QtGui.QWidget):

    def __init__(self, parent=None):
        super(Support, self).__init__(parent)

        self.supportTab()


    def supportTab(self):

        view = QtWebKit.QWebView()

        url = "http://www.google.com"
        view.load(QtCore.QUrl(url))

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(view)

        self.setLayout(vbox)

Can you please tell me how I can solve this?

Thanks in advance.


Solution

  • in main.py:

    make the tab2 addressable, and add code to listen to tab change event:

        #...
        self.tab2 = support
    
        self.tabs.addTab(tab1,"tab1")
        self.tabs.addTab(self.tab2,"SUPPORT")
        #
        self.tabs.currentChanged.connect(self.load_on_show)
    

    Then add the action

    def load_on_show(self):
        idx = self.tabs.currentIndex()
        if idx == 1:
            url = "http://www.google.com"
            print url
            self.tab2.load_url(url)
    

    At last, in tab_file.py [i can't use a dash, have to use an underscore!]:

    Make view addressable, again (self.view) and add code

    def load_url(self, url):
        self.view. load(QtCore.QUrl(url))
    

    Does this help?