SDL渲染RGB数据到Qt中的控件通过定时器刷新
SdlQtRGB.h
#pragma once #include#include "ui_SdlQtRGB.h" class SdlQtRGB : public QWidget { Q_OBJECT public: SdlQtRGB(QWidget *parent = Q_NULLPTR); ~SdlQtRGB(); private: Ui::SdlQtRGBClass ui; void timerEvent(QTimerEvent* evt) override; };
SdlQtRGB.cpp
#include "SdlQtRGB.h" #include "sdl/SDL.h" #include#pragma comment(lib, "SDL2.lib") using namespace std; static SDL_Window* sdl_win = nullptr; static SDL_Renderer* sdl_render = nullptr; static SDL_Texture* sdl_texture = nullptr; static unsigned char* rgb = nullptr; static int sdl_width = 0; static int sdl_height = 0; static int pixel_size = 4; void SdlQtRGB::timerEvent(QTimerEvent* evt) { SDL_Rect rect; static unsigned char tmp = 255; rect.x = 0; rect.y = 0; rect.w = sdl_width; rect.h = sdl_height; for (int i = 0; i < sdl_height; i++) { int b = i * sdl_width * pixel_size; for (int j = 0; j < sdl_width * pixel_size; j += pixel_size) { rgb[b + j] = 0; // B rgb[b + j + 1] = tmp; // G rgb[b + j + 2] = 0; // R rgb[b + j + 3] = 0; // A } } tmp--; SDL_RenderClear(sdl_render); SDL_UpdateTexture(sdl_texture, nullptr, rgb, sdl_width * pixel_size); SDL_RenderCopy(sdl_render, sdl_texture, nullptr, &rect); SDL_RenderPresent(sdl_render); } SdlQtRGB::SdlQtRGB(QWidget *parent) : QWidget(parent) { ui.setupUi(this); sdl_width = ui.label->width(); sdl_height = ui.label->height(); // 初始化 SDL if (SDL_Init(SDL_INIT_VIDEO)) { cout << SDL_GetError() << endl; } // 创建窗口 sdl_win = SDL_CreateWindowFrom((void*)ui.label->winId()); // 通过 Qt 控件中的句柄来创建窗口 if (!sdl_win) { cout << SDL_GetError() << endl; } // 创建渲染器 sdl_render = SDL_CreateRenderer(sdl_win, -1, SDL_RENDERER_ACCELERATED); if (!sdl_render) { cout << SDL_GetError() << endl; } // 创建材质 sdl_texture = SDL_CreateTexture(sdl_render, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, sdl_width, sdl_height); if (!sdl_texture) { cout << SDL_GetError() << endl; } rgb = new unsigned char[sdl_width * sdl_height * pixel_size]; startTimer(10); // 每过10ms就会调用一次 timerEvent,1s大约有100帧的图像 } SdlQtRGB::~SdlQtRGB() { delete[] rgb; }
每过10ms就进行一次图像的渲染。



