widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
void paintEvent(QPaintEvent *e);
void timerEvent(QTimerEvent *e);
~Widget();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QtWidgets>
#include <QImage>
#include <QPixmap>
#include <QElapsedTimer>
#include <iostream>
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
startTimer(100);
}
Widget::~Widget()
{
delete ui;
}
void Widget::timerEvent(QTimerEvent *e)
{
update();
}
void Widget::paintEvent(QPaintEvent *e)
{
//获取QScreen
static QScreen *scr = nullptr;
if(!scr)
{
scr = QGuiApplication::primaryScreen();
if (const QWindow *window = windowHandle())
scr = window->screen();
if (!scr)
return;
}
//截取全屏
static QImage * image = NULL;
QElapsedTimer tm;
tm.start();
// QPixmap pix = scr->grapWindow(windowHandle()); //HWND
QPixmap pix = scr->grabWindow(0);
pix.toImage().bits();
std::cout<<tm.restart()<<"|"<<std::endl;
//绘制截屏
QPainter p;
p.begin(this);
p.drawImage(QPoint(0,0),pix.toImage());
p.end();
}
widget.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Widget</class>
<widget class="QWidget" name="Widget">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>Widget</string>
</property>
</widget>
<resources/>
<connections/>
</ui>
main.cpp
#include "widget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}