문제

I am trying something basic with QWebView in PyQt4. I want to just load a URL. What is strange is that, when I put the QWebView in a function call, it doesn't work, but when it's inline, it does work.

So, the following code works as expected:

if __name__ == '__main__':
    app = QApplication(sys.argv)
    web = QWebView()
    web.load(QUrl('http://www.google.com'))
    web.setFixedSize(500, 500)
    web.show()
    sys.exit(app.exec_())

However, when I move the QWebView code into a function, as shown below, the web view never opens. Instead, the application just appears to hang.

def openPage():
    web = QWebView()
    web.load(QUrl('http://www.google.com'))
    web.setFixedSize(500, 500)
    web.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    openPage()
    sys.exit(app.exec_())

What is going on here? This doesn't seem to make sense.

도움이 되었습니까?

해결책

In openPage you bind the web view object to a local variable web. The web view is automatically destroyed when the variable goes out of scope (when the function returns). You need to keep a reference to the view, perhaps by return like this:

def openPage():
    web = QWebView()
    web.load(QUrl('http://www.google.com'))
    web.setFixedSize(500, 500)
    web.show()
    return web

if __name__ == '__main__':
    app = QApplication(sys.argv)
    web = openPage()
    sys.exit(app.exec_())
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top