Skip to content

Instantly share code, notes, and snippets.

@timo
Created May 1, 2012 19:47
Show Gist options
  • Save timo/2570865 to your computer and use it in GitHub Desktop.
Save timo/2570865 to your computer and use it in GitHub Desktop.
crash due to improper reference counting in pyside and pyqt4
implementation = "PySide"
if implementation == "PySide":
from PySide.QtCore import *
from PySide.QtGui import *
else:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
import random
keepalive = [ "comment out string from this list for a crash"
#,"string"
#,"qimage"
#,"qpixmap"
]
# setting this to true will fix the bug
make_copy_save_the_day = False
# a silly 150x150 pixel gradient
def make_image():
pixel = lambda r, g, b: chr(0) + chr(int(r * 255)) + chr(int(g * 255)) + chr(int(b * 255))
pixels = []
for y in range(150):
for x in range(150):
pixels.append(pixel(y / 150., x / 150., 0))
return "".join(pixels)
class MyPaintedWidget(QWidget):
references = []
def __init__(self):
super(MyPaintedWidget, self).__init__()
self.t = QTimer(self)
self.t.timeout.connect(self.set_image)
self.t.start(100)
self.set_image()
def set_image(self):
image = make_image()
if "string" in keepalive: self.references.append(image)
if make_copy_save_the_day:
# this copy is made before image gets invalidated
image = QImage(buffer(image), 150, 150, QImage.Format_RGB32).copy()
else:
image = QImage(buffer(image), 150, 150, QImage.Format_RGB32)
if "qimage" in keepalive: self.references.append(image)
self.image = QPixmap.fromImage(image)
if "qpixmap" in keepalive: self.references.append(self.image)
self.update()
def paintEvent(self, event):
qp = QPainter(self)
qp.drawPixmap(event.rect(), self.image, event.rect())
del qp
def main():
app = QApplication(sys.argv)
w = MyPaintedWidget()
w.show()
app.exec_()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment