Qt學習筆記-使用QScreen對螢幕進行截圖(可全屏,可部分)

IT1995發表於2020-04-07

執行截圖如下:

 

原始碼如下:

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();

private slots:
    void on_pushButton_clicked();

private:
    Ui::Widget *ui;
};

#endif // WIDGET_H

main.cpp

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

widget.cpp

#include "widget.h"
#include "ui_widget.h"
#include <QWindow>
#include <QDebug>
#include <QPixmap>
#include <QScreen>
#include <QLabel>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_clicked()
{
    QWindow *window=windowHandle();
    QScreen *screen=window->screen();

    QPixmap pixmap=screen->grabWindow(0);
    QLabel *label=new QLabel;
    label->setPixmap(pixmap);
    label->show();

    pixmap.save("C:\\Users\\Administrator\\Desktop\\1.png");
}

被截圖的檔案:

相關文章