目前我自己正在尝试做类似的事情。我采用的方法是创建 QGraphicsScene 的子类并覆盖 QGraphicsScene::sceneChanged 事件。然后如下(伪代码):
QApplication app;
MyGraphicsScene* mgs = new MyGraphicsScene();
MyWidget* mw = new MyWidget();
mgs->addWidget(mw);
现在每次发生更改时都会调用您的 sceneChanged。在那里你可以得到场景的快照作为 QImage。在我的情况下,我将像素数据移动到纹理并将其渲染为我的游戏的覆盖:
void QEOverlay::sceneChanged(QList<QRectF> list)
{
//loop through all screen areas that changed
foreach(QRectF rect, list)
{
//generate a rectangle that is a while number, and fits withing the screen
if(rect.x() < 0) rect.setX(0);
if(rect.y() < 0) rect.setY(0);
if(rect.right() > _width) rect.setRight(_width);
if(rect.bottom() > _height) rect.setRight(_height);
rect = QRectF(Round(rect.x()),Round(rect.y()),Round(rect.width()),Round(rect.height()));
//Create an image, create a qpainter, fill the image with transparent color, and then render a part of the scene to it
QImage image(rect.width(),rect.height(),QImage::Format_ARGB32);
QPainter p(&image);
image.fill(0);
render(&p,image.rect(),rect);
if(tex.lock())
{
for (u32 y = 0; y < image.height(); y++)
{
for (u32 x = 0; x < image.width(); x++)
{
QRgb pix = image.pixel(x, y);
tex.color(x + rect.left(), y + rect.top(), Color(qRed(pix), qGreen(pix), qBlue(pix), qAlpha(pix)));
}
}
tex.unlock();
}
}
}
这种方法存在问题。您仍然需要将键盘和鼠标输入事件重定向到您的子类。这对我来说不是很好,有一些问题,比如鼠标点击没有聚焦 QLineEdit 或 QWebView 中的元素。