Embedding SDL 2 in QT widget

Having scoured the web and found nothing but useless information I thought I should share my solution to embedding a SDL 2 window inside a QT widget. The following code will embed a SDL window inside a ‘openGLWidget’ under the main window ‘central widget’ and display a red background.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 
#include "mainwindow.h"
 
MainWindow::MainWindow(QWidget *parent)
	: QMainWindow(parent),
	ui(new Ui::MainWindowClass)
{
	ui->setupUi(this);
	show();
	image_w_ = 960;
	image_h_ = 544;
 
	if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
		fprintf(stderr, "Could not initialize SDL - %s\n", SDL_GetError());
		exit(1);
	}
	ui->openGLWidget->resize(image_w_, image_h_);
	sdlWindow = SDL_CreateWindowFrom((void*)ui->openGLWidget->winId());
	if (!sdlWindow) {
		fprintf(stderr, "SDL: failed to create window: %s\n", SDL_GetError());
	}
	sdlRenderer = SDL_CreateRenderer(sdlWindow, -1, NULL);
	if (!sdlWindow) {
		fprintf(stderr, "SDL: failed to create renderer: %s\n", SDL_GetError());
	}
	sdlTexture = SDL_CreateTexture(sdlRenderer,
		SDL_PIXELFORMAT_IYUV,
		SDL_TEXTUREACCESS_STREAMING,
		image_w_,
		image_h_);
	if (!sdlTexture) {
		fprintf(stderr, "SDL: failed to create SDl texture - exiting\n");
	}
	SDL_SetRenderDrawColor(sdlRenderer, 255, 0, 0, 255);
	SDL_RenderClear(sdlRenderer);
	SDL_RenderPresent(sdlRenderer);
}
 
MainWindow::~MainWindow()
{
 
}

Leave a Comment