一、前言
螢幕截圖控件在我的很多項目中都有用到,尤其是嵌入式的系統上的軟體,因為在嵌入式系統中,基本上系統都很精簡,甚至連UI都沒有,開機之後直接運作的就是Qt程式,很多時候需要對軟體進行截圖儲存下來,用來編寫文檔和介紹,還有産品彩頁之類的,畢竟在闆子上直接運作的效果是最好的,還有一種辦法是将系統編譯成win的版本,用系統的截圖來,但是嵌入式上很多代碼其實很不友善在win上運作,甚至沒法運作,而且還要外接很多接口來得到真正的運作效果,是以還是采用直接在闆子上的Qt程式中直接內建截圖的功能,需要的時候直接滑鼠右鍵彈出來選擇即可。
二、代碼思路
ScreenWidget::ScreenWidget(QWidget *parent) : QWidget(parent)
{
//this->setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint);
menu = new QMenu(this);
menu->addAction("儲存目前截圖", this, SLOT(saveScreen()));
menu->addAction("儲存全屏截圖", this, SLOT(saveFullScreen()));
menu->addAction("截圖另存為", this, SLOT(saveScreenOther()));
menu->addAction("全屏另存為", this, SLOT(saveFullOther()));
menu->addAction("退出截圖", this, SLOT(hide()));
//取得螢幕大小
screen = new Screen(QApplication::desktop()->size());
//儲存全屏圖像
fullScreen = new QPixmap();
}
void ScreenWidget::paintEvent(QPaintEvent *)
{
int x = screen->getLeftUp().x();
int y = screen->getLeftUp().y();
int w = screen->getRightDown().x() - x;
int h = screen->getRightDown().y() - y;
QPainter painter(this);
QPen pen;
pen.setColor(Qt::green);
pen.setWidth(2);
pen.setStyle(Qt::DotLine);
painter.setPen(pen);
painter.drawPixmap(0, 0, *bgScreen);
if (w != 0 && h != 0) {
painter.drawPixmap(x, y, fullScreen->copy(x, y, w, h));
}
painter.drawRect(x, y, w, h);
pen.setColor(Qt::yellow);
painter.setPen(pen);
painter.drawText(x + 2, y - 8, tr("截圖範圍:( %1 x %2 ) - ( %3 x %4 ) 圖檔大小:( %5 x %6 )")
.arg(x).arg(y).arg(x + w).arg(y + h).arg(w).arg(h));
}
void ScreenWidget::showEvent(QShowEvent *)
{
QPoint point(-1, -1);
screen->setStart(point);
screen->setEnd(point);
#if (QT_VERSION <= QT_VERSION_CHECK(5,0,0))
*fullScreen = fullScreen->grabWindow(QApplication::desktop()->winId(), 0, 0, screen->width(), screen->height());
#else
QScreen *pscreen = QApplication::primaryScreen();
*fullScreen = pscreen->grabWindow(QApplication::desktop()->winId(), 0, 0, screen->width(), screen->height());
#endif
//設定透明度實作模糊背景
QPixmap pix(screen->width(), screen->height());
pix.fill((QColor(160, 160, 160, 200)));
bgScreen = new QPixmap(*fullScreen);
QPainter p(bgScreen);
p.drawPixmap(0, 0, pix);
}
三、效果圖

四、開源首頁
以上作品完整源碼下載下傳都在開源首頁,會持續不斷更新作品數量和品質,歡迎各位關注。