当我将图像放大 100 倍时,Qt 程序开始滞后

问题描述 投票:0回答:1

我想将上传的图像缩放 100 倍,但当我通过鼠标滚轮事件增加它时,我的程序开始滞后。我尝试了不同的方法来解决该问题,但还没有找到解决方案。我通过标签显示我的图像。标签名称是 Screen。

void MainWindow::wheelEvent(QWheelEvent *event)
{
 core->rayanimset.ScaleOn= true;

 if(event->angleDelta().y()>0)
 {
    if (core->rayanimset.ScaledF * 1.1 <= 100)
    {
       core->rayanimset.ScaledF*=1.1;
    }
}
else
{
    if (core->rayanimset.ScaledF * 0.9 >= 0.1)
    {
        core->rayanimset.ScaledF*= 0.9;
    }
}

updateImage();

event->accept();

}

void MainWindow::updateImage()
{
if (!core->Img.empty())
{
    onprocessFinished(core->Img);
}

}

void MainWindow::onprocessFinished(cv::Mat img)
{

if(core->rayanimset.ScaleOn)
{
    qimg = matToImage(img);
    qimg= qimg.scaled(qimg.width()*core->rayanimset.ScaledF, qimg.height()*core->rayanimset.ScaledF, Qt::KeepAspectRatio, Qt::SmoothTransformation);
}
else
{
    qimg = matToImage(img);
}

    ui->Screen->setPixmap(QPixmap::fromImage(qimg));
    ui->Screen->setAlignment(Qt::AlignCenter); 

}

c++ qt user-interface scale qt6
1个回答
0
投票

您可以覆盖

paintEvent
并将缩放
QTransform
应用于
QPainter
并绘制原始图像,而不是调整图像大小。

#include <QApplication>
#include <QLabel>
#include <QObject>
#include <QPainter>
#include <QWheelEvent>
#include <QMessageBox>
#include <QDir>
#include <QScrollArea>

class Label : public QWidget {
public:
    void setImage(const QImage& image) {
        mImage = image;
        mScale = 1.0;
        scaleChanged();
    }

    void scaleChanged() {
        mTransform = QTransform().scale(mScale, mScale);
        QSize hint = sizeHint();
        resize(hint.width(), hint.height());
        update();
    }

protected:
    QImage mImage;
    double mScale  = 1.0;
    QTransform mTransform;
    void wheelEvent(QWheelEvent *event) override {
        if(event->angleDelta().y()>0) {
            mScale = mScale * 1.1;
        } else {
            mScale = mScale / 1.1;
        }
        scaleChanged();
    }
    void paintEvent(QPaintEvent *event) override {
        if (mImage.isNull()) {
            return;
        }
        QPainter painter(this);
        painter.setTransform(mTransform);
        painter.drawImage(QPoint(0,0), mImage);
    }
public:
    QSize sizeHint() const override {
        if (mImage.isNull()) {
            return QSize(100,100);
        }
        int w = mScale * (double) mImage.width();
        int h = mScale * (double) mImage.height();
        return QSize(w, h);
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    Label label;
    QString path = QDir(qApp->applicationDirPath()).filePath("image.png");
    QImage image(path);
    if (image.isNull()) {
        QMessageBox::critical(0, "Error", "Failed to load image");
    } else {
        label.setImage(image);
    }

    QScrollArea area;
    area.setWidget(&label);
    area.setWidgetResizable(false);
    area.show();

    return a.exec();
}
© www.soinside.com 2019 - 2024. All rights reserved.