首页 > 解决方案 > 嵌入 PyQt 时 Pygame 不返回事件

问题描述

我正在测试一个应用程序,用户界面使用 PyQt4,其中嵌入了 Pygame。可以这么说,它使用计时器来“更新”自身,并且在 timerEvent 函数中 Pygame 尝试检索所有检测到的事件。问题是,Pygame 没有检测到任何事件。

这是我的代码的极简版本

#!/etc/python2.7
from PyQt4 import QtGui
from PyQt4 import QtCore
import pygame
import sys

class ImageWidget(QtGui.QWidget):
    def __init__(self,surface,parent=None):
        super(ImageWidget,self).__init__(parent)
        w=surface.get_width()
        h=surface.get_height()
        self.data=surface.get_buffer().raw
        self.image=QtGui.QImage(self.data,w,h,QtGui.QImage.Format_RGB32)

        self.surface = surface

        self.timer = QtCore.QBasicTimer()
        self.timer.start(500, self)

    def timerEvent(self, event):
        w=self.surface.get_width()
        h=self.surface.get_height()
        self.data=self.surface.get_buffer().raw
        self.image=QtGui.QImage(self.data,w,h,QtGui.QImage.Format_RGB32)
        self.update()

        for ev in pygame.event.get():
            if ev.type == pygame.MOUSEBUTTONDOWN:
                print "Mouse down"

    def paintEvent(self,event):
        qp=QtGui.QPainter()
        qp.begin(self)
        qp.drawImage(0,0,self.image)
        qp.end()


class MainWindow(QtGui.QMainWindow):
    def __init__(self,surface,parent=None):
        super(MainWindow,self).__init__(parent)
        self.setCentralWidget(ImageWidget(surface))



pygame.init()
s=pygame.Surface((640,480))
s.fill((64,128,192,224))
pygame.draw.circle(s,(255,255,255,255),(100,100),50)

app=QtGui.QApplication(sys.argv)
w=MainWindow(s)
w.show()
app.exec_()

当 Pygame 窗口嵌入 PyQt 应用程序时,如何获取 Pygame 事件?

标签: pythonpyqtpygamepygame-surface

解决方案


你不能。


TL; 博士;

您不能也不应该组合 2 个具有自己的事件循环的库,例如现在 Qt 事件循环正在阻塞 pygame 事件循环。


推荐阅读