David Ludwig
David Ludwig

Reputation: 1037

Taking Screenshot of Full Desktop with Qt5

I figured out how to take a screenshot of the desktop today with Qt5 from an included example which gets the primary screen, grabs it, and then saves it.

I'm translating the code from Python without testing so if there's a small syntax error, then yeah you know. So I can easily take a screenshot of the primary screen with:

QApplication a(argv, argc);

QScreen *screen = a.primaryScreen();

QPixmap screenshot = screen->grabWindow(0);

screenshot.save('screenshot.png', 'png');

This will (obviously) take a screenshot of the primary monitor. The problem is I need to take a screenshot of all of the monitors. So I came up with this:

QList<QScreen*> screens = a.screens();
QScreen *screen;
QPixmap screenshot;

for(int i = 0; i < screens.length(); i++){
    screen = screens.at(i);
    screenshot = screen->grabWindow(0);
    screenshot.save(QString::number(i) + ".png", 'png');
}
//takes and saves two screenshots on my end

This finds both of my monitors but the saved images are all a screenshot of the primary monitor and I can't figure out how to get the others. I've been playing with this for a few hours now and still can't figure it out. So can someone help me out?

Upvotes: 3

Views: 3429

Answers (1)

David Ludwig
David Ludwig

Reputation: 1037

I figured out a simple fix for this problem. When I was looking through the documentation recently, I found that the 'getWindow' method had default parameters of

(x = 0, y = 0, width = -1, height = -1)

So no matter what screen I called the getWindow method with, it kept giving me the same geometry. So to fix this, it's simply:

//Screen geometry
QRect g = screen->geometry();

//Take the screenshot using the geometry of the screen
QPixmap screenShot = screen->grabWindow(0, g.x(), g.y(), g.width(), g.height());

Upvotes: 6

Related Questions