Skip to content

Instantly share code, notes, and snippets.

@xim
Last active September 2, 2015 17:15
Show Gist options
  • Save xim/b5c6bc5b05a7c3340f96 to your computer and use it in GitHub Desktop.
Save xim/b5c6bc5b05a7c3340f96 to your computer and use it in GitHub Desktop.
#include "grabberdialog.h"
#include <QDebug>
#include <QGuiApplication>
#include <QLabel>
#include <QPixmap>
#include <QPushButton>
#include <QScreen>
#include <QVBoxLayout>
#include <QWindow>
GrabberDialog::GrabberDialog(QWidget *parent)
: QDialog(parent)
{
setLayout(new QVBoxLayout);
QPushButton *captureButton = new QPushButton("Capture current screen", this);
connect(captureButton, &QPushButton::clicked, this, &GrabberDialog::grabCurrentScreen);
layout()->addWidget(captureButton);
image = new QLabel;
layout()->addWidget(image);
}
void GrabberDialog::grabCurrentScreen() {
QScreen *thisScreen = windowHandle()->screen();
if (!thisScreen)
thisScreen = QGuiApplication::primaryScreen();
auto screenGeometry = thisScreen->geometry();
qDebug() << "Capturing window at" << geometry() << "from screen" << screenGeometry << "with ratio" << thisScreen->devicePixelRatio();
QPixmap capture = thisScreen->grabWindow(winId(), screenGeometry.x(), screenGeometry.y(), screenGeometry.width() / thisScreen->devicePixelRatio(), screenGeometry.height() / thisScreen->devicePixelRatio());
capture = capture.scaledToWidth(capture.width() / 3, Qt::SmoothTransformation);
image->setPixmap(capture);
image->resize(capture.width(), capture.height());
}
#ifndef GRABBERDIALOG_H
#define GRABBERDIALOG_H
#include <QDialog>
class QLabel;
class GrabberDialog : public QDialog
{
Q_OBJECT
public:
GrabberDialog(QWidget *parent = 0);
private slots:
void grabCurrentScreen();
private:
QLabel *image;
};
#endif // GRABBERDIALOG_H
#include "grabberdialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
GrabberDialog w;
w.show();
return a.exec();
}
#-------------------------------------------------
#
# Project created by QtCreator 2015-08-08T10:25:16
#
#-------------------------------------------------
QT += core gui
CONFIG += c++11
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = screengrabber
TEMPLATE = app
SOURCES += main.cpp\
grabberdialog.cpp
HEADERS += grabberdialog.h
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment