转换 QObject 子类实例
Casting a QObject subclass instance
我有一个 QPixmap
subclass 和额外的 class 方法 make
:
class Screenshot(QtGui.QPixmap):
@classmethod
def make(cls):
desktop_widget = QtGui.QApplication.desktop()
image = cls.grabWindow(
desktop_widget.winId(), rect.x(), rect.y(), rect.width(), rect.height())
import ipdb; ipdb.set_trace()
image.save()
return image
当我调用 Screenshot.make()
时,传递了正确的 class cls
,但是通过 cls.grabWindow
创建的实例不是 Screenshot
:
ipdb> ...py(30)make()
29 import ipdb; ipdb.set_trace()
---> 30 image.save()
31 return image
ipdb> cls
<class 'viewshow.screenshot.Screenshot'>
ipdb> image
<PyQt4.QtGui.QPixmap object at 0x7f0f8c4a9668>
更短:
ipdb> Screenshot.grabWindow(desktop_widget.winId())
<PyQt4.QtGui.QPixmap object at 0x7f0f8154c438>
如何获取Screenshot
实例?
所有Screenshot
继承自QPixmap
的方法都会return一个QPixmap
,所以你需要显式地创建和return一个[=的实例11=] 代替。
唯一真正的问题是避免低效的复制。但是,QPixmap
提供了一个非常快速的复制构造函数来执行此操作,因此您只需要这样的东西:
class Screenshot(QtGui.QPixmap):
@classmethod
def make(cls):
...
image = cls.grabWindow(...)
return cls(image)
我有一个 QPixmap
subclass 和额外的 class 方法 make
:
class Screenshot(QtGui.QPixmap):
@classmethod
def make(cls):
desktop_widget = QtGui.QApplication.desktop()
image = cls.grabWindow(
desktop_widget.winId(), rect.x(), rect.y(), rect.width(), rect.height())
import ipdb; ipdb.set_trace()
image.save()
return image
当我调用 Screenshot.make()
时,传递了正确的 class cls
,但是通过 cls.grabWindow
创建的实例不是 Screenshot
:
ipdb> ...py(30)make()
29 import ipdb; ipdb.set_trace()
---> 30 image.save()
31 return image
ipdb> cls
<class 'viewshow.screenshot.Screenshot'>
ipdb> image
<PyQt4.QtGui.QPixmap object at 0x7f0f8c4a9668>
更短:
ipdb> Screenshot.grabWindow(desktop_widget.winId())
<PyQt4.QtGui.QPixmap object at 0x7f0f8154c438>
如何获取Screenshot
实例?
所有Screenshot
继承自QPixmap
的方法都会return一个QPixmap
,所以你需要显式地创建和return一个[=的实例11=] 代替。
唯一真正的问题是避免低效的复制。但是,QPixmap
提供了一个非常快速的复制构造函数来执行此操作,因此您只需要这样的东西:
class Screenshot(QtGui.QPixmap):
@classmethod
def make(cls):
...
image = cls.grabWindow(...)
return cls(image)