【问题标题】:QtWebkit segfaults when passed a QObject传递 QObject 时 QtWebkit 段错误
【发布时间】:2012-09-11 05:53:59
【问题描述】:

每当我从另一个QObject 的方法返回QObject 时,QtWebkit 段错误。

这是我能想到的最简单的测试用例(它适用于 PySide 和 PyQt4):

#!/usr/bin/env python2

import sys

try:
  from PyQt4.QtCore import QObject, QVariant, pyqtProperty
  from PyQt4.QtGui import QApplication
  from PyQt4.QtWebKit import QWebView

  Property = pyqtProperty
except ImportError:
  from PySide.QtCore import QObject, Property
  from PySide.QtGui import QApplication
  from PySide.QtWebKit import QWebView

class TestObject(QObject):
  @Property(str)
  def property(self):
    return 'foo'

class TestObjectContainer(QObject):
  @Property(QObject)  # Swapping QObject with TestObject doesn't fix it
  def object(self):
    return TestObject()

if __name__ == '__main__':
  application = QApplication(sys.argv)

  browser = QWebView()
  frame = browser.page().mainFrame()

  frame.addToJavaScriptWindowObject('container', TestObjectContainer())
  frame.addToJavaScriptWindowObject('test_object', TestObject())

  browser.show()

  #frame.evaluateJavaScript('test_object.property')
  frame.evaluateJavaScript('container.object.property')

  sys.exit(application.exec_())

这是奇怪的部分:

test_object.property;       // This doesn't segfault
container.object.property;  // This does

有没有办法像这样返回QObjects?是我做错了什么,还是这是一个错误?


我最终在@HYRY's answer 的帮助下创建了一个简单的包装类:

class WebkitQObject(QObject):
  def __init__(self):
    super(WebkitQObject, self).__init__()
    self.__cache__ = []

  def store(self, item):
    self.__cache__.append(item)

    return self.__cache__[-1]

现在,此代码稍作修改即可工作:

class TestObjectContainer(WebkitQObject):
  @Property(QObject)
  def object(self):
    return self.store(TestObject())

【问题讨论】:

    标签: python segmentation-fault pyqt4 pyside


    【解决方案1】:

    您需要一个对 QObject 的 Python 引用才能使其保持活动状态。您可以通过更改以下代码来测试这一点,

    class TestObjectContainer(QObject):
      @Property(QObject)
      def object(self):
        self.tmp = TestObject()
        return self.tmp
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-19
      • 1970-01-01
      相关资源
      最近更新 更多