Qt 截取屏幕的小demo

无代码无真相。我不啰嗦。

demo效果图:

demo效果图

布局:

创建一个图形工程,创建以下布局:,分别使用了网状布局,横向布局, 垂直布局。 界面的主布局为垂直布局。

布局

右键点击 新建截图 按钮,选择clicked() 信号, 跳转到相对应的槽填写以下代码

void screenshot::on_newScreenshot_clicked()

{

if(ui->checkBox->isChecked())

{

this->hide();

this->timer =new QTimer;

QObject::connect(timer,SIGNAL(timeout()),this,SLOT(shotScreen()));

timer->start(ui->spinBox->value()*1000);

//如果当前复选框为选中,那么通过定时器来触发截屏信号

}

else

{

qApp->beep();

}

}

以上代码使用了一个自定义的槽, 所以要在头文件中声明

private slots:

void shotScreen();

在源文件中实现槽:

void screenshot::shotScreen()

{

pixmap=QPixmap::grabWindow(QApplication::desktop()->winId());

ui->screenLabel->setPixmap(pixmap.scaled(ui->screenLabel->size()));

this->timer->stop();

this->show();

}

每一个窗口都有自己的私有的id, 如同进程号一样, 当访问一个窗口后, 获得当前桌面的id , 通过grabWindow()函数抓取图片并赋给pixmap。 当前定时器撤销, 让窗口再次显示出来。

将当前的图片保存到一个指定的目录下,右键单击 保存截图 按钮, 选择clicked()信号,填写以下代码:

void screenshot::on_saveScrenshot_clicked()

{

QString format = "png";

QString initialPath = QDir::currentPath() + tr("/untitled.") + format;

QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"),

initialPath,

tr("%1 Files (*.%2);;All Files (*)")

.arg(format.toUpper())

.arg(format));

if (!fileName.isEmpty())

pixmap.save(fileName, format.toAscii());

}

screenshot.cpp

#include "screenshot.h" #include "ui_screenshot.h" Screenshot::Screenshot(QWidget *parent) : QMainWindow(parent), ui(new Ui::Screenshot) { ui->setupUi(this); QObject::connect(ui->shotScreenButton,SIGNAL(clicked()),this,SLOT(newShotScreenSlot())); QObject::connect(ui->saveButton,SIGNAL(clicked()),this,SLOT(saveScreenSlot())); } Screenshot::~Screenshot() { delete ui; } void Screenshot::newShotScreenSlot() { if(ui->hideCheckBox->isChecked()) { this->hide(); this->timer =new QTimer; QObject::connect(this->timer,SIGNAL(timeout()),this,SLOT(shotScreenSlot())); this->timer->start(ui->timeSpinBox->value()*1000); } else { qApp->beep(); } } void Screenshot::shotScreenSlot() { this->pixmap= QPixmap::grabWindow(QApplication::desktop()->winId()); ui->screenLabel->setPixmap(pixmap.scaled(ui->screenLabel->size())); this->timer->stop(); this->show(); } #include <QFileDialog> #include <QDir> #include <QMessageBox> void Screenshot::saveScreenSlot() { QString fileName=QFileDialog::getSaveFileName(this,"Screen Save",QDir::currentPath()); if(!fileName.isEmpty()) { pixmap.save(fileName); } else { QMessageBox::information(this,"Error Message","Select a name "); return; } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值