如何正确关闭PyQt的qt应用程序?

2024-05-13 12:17:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Qt一点都不了解,但我正试图厚着脸皮从其他地方借用代码(http://sieral.netmanagers.com.ar/weblog/posts/BB901.html#discus_线程). ;)

我有个问题。当我第一次运行test()时,一切都很顺利。然而,当我第二次运行它时,我得到了令人讨厌的分段错误。我怀疑问题是我没有正确地结束qt。我应该对这个程序做些什么改变才能使它多次工作?提前谢谢!在

from PyQt4 import QtCore, QtGui, QtWebKit
import logging

logging.basicConfig(level=logging.DEBUG)

class Capturer(object):
    """A class to capture webpages as images"""

    def __init__(self, url, filename, app):
        self.url = url
        self.app = app
        self.filename = filename
        self.saw_initial_layout = False
        self.saw_document_complete = False

    def loadFinishedSlot(self):
        self.saw_document_complete = True
        if self.saw_initial_layout and self.saw_document_complete:
            self.doCapture()

    def initialLayoutSlot(self):
        self.saw_initial_layout = True
        if self.saw_initial_layout and self.saw_document_complete:
            self.doCapture()

    def capture(self):
        """Captures url as an image to the file specified"""
        self.wb = QtWebKit.QWebPage()
        self.wb.mainFrame().setScrollBarPolicy(
            QtCore.Qt.Horizontal, QtCore.Qt.ScrollBarAlwaysOff)
        self.wb.mainFrame().setScrollBarPolicy(
            QtCore.Qt.Vertical, QtCore.Qt.ScrollBarAlwaysOff)
        self.wb.loadFinished.connect(self.loadFinishedSlot)
        self.wb.mainFrame().initialLayoutCompleted.connect(
            self.initialLayoutSlot)
        logging.debug("Load %s", self.url)
        self.wb.mainFrame().load(QtCore.QUrl(self.url))

    def doCapture(self):
        logging.debug("Beginning capture")
        self.wb.setViewportSize(self.wb.mainFrame().contentsSize())
        img = QtGui.QImage(self.wb.viewportSize(), QtGui.QImage.Format_ARGB32)
        painter = QtGui.QPainter(img)
        self.wb.mainFrame().render(painter)
        painter.end()
        img.save(self.filename)
        self.app.quit()

def test():
    """Run a simple capture"""
    app = QtGui.QApplication([])
    c = Capturer("http://www.google.com", "google.png", app)
    c.capture()
    logging.debug("About to run exec_")
    app.exec_()

DEBUG:root:Load http://www.google.com
QObject::connect: Cannot connect (null)::configurationAdded(QNetworkConfiguration) to QNetworkConfigurationManager::configurationAdded(QNetworkConfiguration)
QObject::connect: Cannot connect (null)::configurationRemoved(QNetworkConfiguration) to QNetworkConfigurationManager::configurationRemoved(QNetworkConfiguration)
QObject::connect: Cannot connect (null)::configurationUpdateComplete() to QNetworkConfigurationManager::updateCompleted()
QObject::connect: Cannot connect (null)::onlineStateChanged(bool) to QNetworkConfigurationManager::onlineStateChanged(bool)
QObject::connect: Cannot connect (null)::configurationChanged(QNetworkConfiguration) to QNetworkConfigurationManager::configurationChanged(QNetworkConfiguration)

Process Python segmentation fault (this last line is comes from emacs)

Tags: toselfappurlloggingdefconnectqt
2条回答

QApplication只能初始化一次! 它可以被任意多个捕获实例使用,但是应该在主循环中启动它们。 参见:https://doc.qt.io/qt-4.8/qapplication.html

你也可以试试“del app”应用程序执行_“,但我不确定结果。 (您的原始代码在我的系统上运行良好)

我将使用urllib而不是webkit:

import urllib

class Capturer:
    def capture(self, s_url, s_filename):
        s_file_out, httpmessage = urllib.urlretrieve(s_url, s_filename, self.report)

    def report(self, i_count, i_chunk, i_size):
        print('retrived %5d of %5d bytes' % (i_count * i_chunk, i_size))

def test():
    c = Capturer()
    c.capture("http://www.google.com/google.png", "google1.png")
    c.capture("http://www.google.com/google.png", "google2.png")

if __name__ == '__main__':
    test()

您需要在测试函数之外处理QApplication,有点像singleton(在这里实际上很合适)。在

你能做的就是检查QtCore.qApp是什么(或者如果QApplication.instance应用程序()返回None或其他值),然后才创建qApp,否则,使用全局qApp。在

因为PyQt将应用程序存储在某个地方,所以它不会在test()函数之后被销毁。在

如果您想确保它被正确地处理,只需为它设置一个延迟初始化的singleton。在

相关问题 更多 >