如何整合 Pygame 和 PyQt4? [英] How to integrate Pygame and PyQt4?
本文介绍了如何整合 Pygame 和 PyQt4?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用的是 python 2.7 和 Ubuntu 14.04.
I'm using python 2.7 and Ubuntu 14.04.
我正在尝试做这个为了让我的 pygame 窗口在我的 GUI 中
I'm trying to do this in order to have my pygame window inside my GUI
在某些平台上,可以将 pygame 显示嵌入到已经存在的窗口中.为此,必须将环境变量 SDL_WINDOWID 设置为包含窗口 ID 或句柄的字符串.pygame显示初始化时检查环境变量
所以这就是我所做的:
from PyQt4 import QtGui, QtCore
import os
import subprocess
import sys
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setWindowModality(QtCore.Qt.ApplicationModal)
MainWindow.setFixedSize(800, 600)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.iniMap()
def iniMap(self):
command = "xprop -root _NET_ACTIVE_WINDOW"
output = subprocess.Popen(["/bin/bash", "-c", command], stdout=subprocess.PIPE)
activeWindowID = str(output.communicate()[0].decode("utf-8").strip().split()[-1])
os.environ['SDL_WINDOWID'] = activeWindowID
import pygame
pygame.init()
screen = pygame.display.set_mode((565, 437), pygame.NOFRAME)
class frmMain(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(frmMain, self).__init__(parent, flags=QtCore.Qt.FramelessWindowHint)
self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
self.setupUi(self)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
form = frmMain()
form.show()
sys.exit(app.exec_())
但它不起作用.它只显示我的 PyQt 窗口.不知道是我做错了什么还是pygame无法与PyQt集成
But it doesn't work. It only shows my PyQt window. I don't know whether I'm doing something wrong or pygame just cannot be integrated with PyQt
我应该怎么做才能将我的 pygame 窗口嵌入到 frmMain
中?
What should I do to get my pygame window embedded in frmMain
?
提前致谢.
推荐答案
根据上面的评论,这是一个示例解决方案:
Here is a sample solution as per the comment above:
from PyQt4 import QtGui
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)
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 和 PyQt4?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文