在实际的项目中,有时候需要我们对一些重要的信息进行截屏保存为图片的形式备用,前段时间在做项目的时候需要实现这个功能,当时是需求是按住PrintScreen键然后弹出预览对话框,最后选择保存或者打印图片。在使用MFC做的时候需要安装钩子,来捕获热键PrintScreen按下的过程,那么对于Qt不需要那么复杂,因为我们可以重写keyPressEvent(),来捕获自定义的按键来实现截屏功能。
对于本节的实现的截屏小功能是参照Qt文档进行进行实现的。
对于ScreenShoot.h如下:
#include <QApplication>
#include <QDesktopWidget>
#include <QWidget>
#include <QLabel>
#include <QSpinBox>
#include <QGroupBox>
#include <QPushButton>
#include <QCheckBox>
#include <QVBoxLayout>
#include <QGroupBox>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QScreen>
#include <QWindow>
#include <QTimer>
#include <QResizeEvent>
#include <QFileDialog>
#include <QStandardPaths>
#include <QImageWriter>
#include <QMessageBox>
#include <QKeyEvent>
#include <QPrintDialog>
#include <QPrinter>
#include <QPainter>
#include <QPageLayout>
class ScreenShoot : public QWidget
{
Q_OBJECT
public:
ScreenShoot(QWidget *parent = 0);
~ScreenShoot();
protected:
void resizeEvent(QResizeEvent *event);
void keyPressEvent(QKeyEvent *event);
private slots:
void newScreenshot();
void saveScreenshot();
void shootScreen();
void updateCheckBox();
void printerImage();
void storeImageToPDF();
private:
void updateScreenshotLabel();
QPixmap originalPixmap;
QLabel *screenshotLabel;
QLabel *delayLabel;
QSpinBox *delaySpinBox;
QCheckBox *hideThisWindowCheckBox;
QPushButton *newScreenshotButton;
QPushButton *saveScreenshotButton;
QPushButton *printerBtn;
QPushButton *pdfBtn;
QPushButton *quitButton;
};
我们分别重写resizeEvent事件和keyPressEvent,重写resizeEvent事件是为了在改变界面大小的时候screenshotLabel的大小也会随之发生变化,那么我们通过调整pixmap的大小来实现当拉伸窗口的时候pixmap的大小也随之发生变化。重写keyPressEvent是为了实现自定义截屏按钮,本例中我捕获F1键,当按下F1键的时候执行截屏功能。
同时我们需要实现对应的槽函数:
1.newScreenshot()槽函数想要新的截屏操作。
2.saveScreenshot()槽函数实现保存图片功能。
3. saveScreenshot() 槽函数实现真正的截屏功能。
4.upd