问题描述
我有一个带有附加类方法 make
的 QPixmap
子类:
I have a QPixmap
subclass with additional class method 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()
时,传递了正确的类 cls
,但通过 cls.grabWindow
创建的实例不是截图
:
When I call Screenshot.make()
the correct class cls
is passed, but the instance created via cls.grabWindow
is not a 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
的所有方法都会返回一个 QPixmap
,所以你需要显式地创建并返回一个 Screenshot
的实例.
All the methods Screenshot
inherits from QPixmap
will return a QPixmap
, so you need to explicitly create and return an instance of Screenshot
instead.
唯一真正的问题是避免低效复制.然而,QPixmap
提供了一个非常快速的复制构造函数来实现这一点,所以你所需要的只是这样:
The only real issue is to avoid inefficient copying. However, QPixmap
provides a very fast copy-constructor for doing just that, so all you need is something like this:
class Screenshot(QtGui.QPixmap):
@classmethod
def make(cls):
...
image = cls.grabWindow(...)
return cls(image)
这篇关于投射 QObject 子类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!