0

QtWebkit每当我QObject从 another 的方法返回 a 时,segfaults QObject

这是我能想到的最简单的测试用例(它适用于 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

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


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

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())
4

1 回答 1

1

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

class TestObjectContainer(QObject):
  @Property(QObject)
  def object(self):
    self.tmp = TestObject()
    return self.tmp
于 2012-09-11T06:01:54.820 回答