要在Qt中實作放大鏡功能,您可以建立一個自定義的放大鏡控件,并利用滑鼠事件和繪圖來實作放大鏡效果。
以下是一個簡單的示例代碼,示範如何在Qt中實作放大鏡功能:
#include <QApplication>
#include <QMouseEvent>
#include <QPainter>
#include <QPixmap>
#include <QWidget>
class MagnifierWidget : public QWidget {
Q_OBJECT
public:
explicit MagnifierWidget(QWidget* parent = nullptr)
: QWidget(parent),
zoomFactor(2.0),
radius(100),
pixmap(nullptr) {
setFixedSize(radius * 2, radius * 2);
setMouseTracking(true);
}
void setZoomFactor(double factor) {
zoomFactor = factor;
update();
}
void setRadius(int r) {
radius = r;
setFixedSize(radius * 2, radius * 2);
update();
}
protected:
void mouseMoveEvent(QMouseEvent* event) override {
if (pixmap) {
int x = event->pos().x() - radius;
int y = event->pos().y() - radius;
QPoint sourcePoint(x / zoomFactor, y / zoomFactor);
QRect sourceRect(sourcePoint.x(), sourcePoint.y(), width() / zoomFactor, height() / zoomFactor);
QPixmap zoomedPixmap = pixmap->copy(sourceRect);
QPainter painter(this);
painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
painter.drawPixmap(rect(), zoomedPixmap);
}
}
void paintEvent(QPaintEvent* event) override {
Q_UNUSED(event);
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
if (pixmap) {
painter.drawPixmap(rect(), *pixmap);
} else {
painter.fillRect(rect(), Qt::white);
}
// 繪制放大鏡邊框
painter.setPen(Qt::black);
painter.setBrush(Qt::NoBrush);
painter.drawEllipse(rect().adjusted(0, 0, -1, -1));
}
public slots:
void setPixmap(const QPixmap& pixmap) {
this->pixmap = new QPixmap(pixmap);
update();
}
private:
double zoomFactor; // 縮放因子
int radius; // 放大鏡半徑
QPixmap* pixmap; // 原始圖檔的指針
};
使用示例:
#include <QApplication>
#include <QLabel>
#include <QPixmap>
#include <QVBoxLayout>
#include "magnifierwidget.h"
int main(int argc, char* argv[]) {
QApplication a(argc, argv);
QLabel* imageLabel = new QLabel;
QPixmap pixmap(":/path/to/your/image.jpg");
imageLabel->setPixmap(pixmap);
MagnifierWidget* magnifier = new MagnifierWidget;
magnifier->setPixmap(pixmap);
magnifier->setZoomFactor(2.5); // 設定放大因子,預設為2.0
magnifier->setRadius(100); // 設定放大鏡半徑,預設為100
QVBoxLayout* layout = new QVBoxLayout;
layout->addWidget(imageLabel);
layout->addWidget(magnifier);
QWidget window;
window.setLayout(layout);
window.show();
return a.exec();
}
在上述代碼中,您需要将 :/path/to/your/image.jpg 替換為您自己的圖像路徑。然後,您可以通過調整放大鏡的縮放因子和半徑來适應您的需求。最後,将 MagnifierWidget 置于圖像上方,即可實作放大鏡的功能。
注意:為了使用上述代碼,您需要建立一個名為 "magnifierwidget.h" 的頭檔案,并在其中添加 #include <QWidget> 和 #include <QPixmap>。