点击新建截图按钮:
//点击新建截图的时候
void myWidget::on_newScreenbutton_clicked()
{
if(ui->checkBox->isChecked())
{
this->hide();
}
QTimer::singleShot(ui->spinBox->value()*1000,this,SLOT(dely_screen()));
}
这里singleShot是一个延迟事件函数,第一个参数是时间,第二个参数是指定对象,;第三个参数是槽函数,表示在这个时间长度过后就调用这个槽函数
dely_screen()函数
void myWidget::dely_screen()
{
//准备获取屏幕图像
QScreen *screen=QGuiApplication::primaryScreen();
pixmap=QPixmap();//每次都给pixmap赋空值
pixmap= screen->grabWindow(0);//截图
//将图片的大小按照窗口大小适应放入显示区
ui->scrennlabel->setPixmap(pixmap.scaled(ui->scrennlabel->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation));
if(this->isHidden())
{
this->show();
}
}
重点知识:
1.抓取屏幕的方法(在上面的函数中)
2.setpixmap用法
3.scaled的用法
总代码:
mywidget.h
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
#include<QTimer>
#include<QPixmap>
namespace Ui {
class myWidget;
}
class myWidget : public QWidget
{
Q_OBJECT
public:
explicit myWidget(QWidget *parent = 0);
~myWidget();
protected:
virtual void resizeEvent(QResizeEvent *event);
private slots:
void on_newScreenbutton_clicked();
void on_savebutton_clicked();
void on_exitbutton_clicked();
void dely_screen();
private:
Ui::myWidget *ui;
QTimer *timer;
QPixmap pixmap;//截图保存
int num;
};
#endif // MYWIDGET_H
mywidget.cpp
#include "mywidget.h"
#include "ui_mywidget.h"
#include<QDebug>
#include<QScreen>
#include<QPixmap>
#include<QFileDialog>
#include<QTimer>
myWidget::myWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::myWidget)
{
ui->setupUi(this);
timer=new QTimer(this);
connect(timer,&QTimer::timeout,this,&myWidget::dely_screen);
}
myWidget::~myWidget()
{
delete ui;
}
//点击新建截图的时候
void myWidget::on_newScreenbutton_clicked()
{
if(ui->checkBox->isChecked())
{
this->hide();
}
QTimer::singleShot(ui->spinBox->value()*1000,this,SLOT(dely_screen()));
}
void myWidget::on_savebutton_clicked()
{
const QPixmap *pixmap=ui->scrennlabel->pixmap();
if(pixmap)//如果图片存在的话
{
//进行保存工作,需要头文件QFileDialog
QString path= QFileDialog::getSaveFileName(this,"保存截图");
pixmap->save(path);
}
}
void myWidget::dely_screen()
{
//准备获取屏幕图像
QScreen *screen=QGuiApplication::primaryScreen();
pixmap=QPixmap();//每次都给pixmap赋空值
pixmap= screen->grabWindow(0);//截图
//将图片的大小按照窗口大小适应放入显示区
ui->scrennlabel->setPixmap(pixmap.scaled(ui->scrennlabel->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation));
if(this->isHidden())
{
this->show();
}
}
void myWidget::resizeEvent(QResizeEvent *event)
{
if(ui->scrennlabel->pixmap())
{
ui->scrennlabel->setPixmap(pixmap.scaled(ui->scrennlabel->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation));
}
}
void myWidget::on_exitbutton_clicked()
{
this->close();
}
重点知识:
1.怎样保存一张图片,保存之前要确定这张图片是否存在
2.resizeEvent方法:
这是一个当窗口的大小变化的时候就会自动调用的方法