resizeEvent报错
时间: 2023-08-04 08:39:41 浏览: 120
非常抱歉,我的回答依然有误。`QGraphicsView`并没有`resizeEvent`事件,正确的方法是重写`QGraphicsView`的`resizeEvent`方法。下面是修改后的代码:
```c++
// 创建图片对象
QPixmap qImgSrc = QPixmap::fromImage(QImage(imgsrc.data, imgsrc.cols, imgsrc.rows, QImage::Format_RGB888));
QPixmap qImgBin = QPixmap::fromImage(QImage(imgthreshold.data, imgthreshold.cols, imgthreshold.rows, QImage::Format_RGB888));
// 创建场景对象
QGraphicsScene scene1, scene2;
// 创建图片项并添加到场景中
QGraphicsPixmapItem item1(qImgSrc);
QGraphicsPixmapItem item2(qImgBin);
scene1.addItem(&item1);
scene2.addItem(&item2);
// 设置场景
ui.graphSrc->setScene(&scene1);
ui.graphBin->setScene(&scene2);
// 重写QGraphicsView的resizeEvent方法
class MyGraphicsView1 : public QGraphicsView {
public:
MyGraphicsView1(QGraphicsScene *scene, QWidget *parent = nullptr) : QGraphicsView(scene, parent) {}
protected:
void resizeEvent(QResizeEvent *event) override {
QGraphicsView::resizeEvent(event);
item1.setPixmap(qImgSrc.scaled(size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
}
private:
QGraphicsPixmapItem item1;
QPixmap qImgSrc;
};
class MyGraphicsView2 : public QGraphicsView {
public:
MyGraphicsView2(QGraphicsScene *scene, QWidget *parent = nullptr) : QGraphicsView(scene, parent) {}
protected:
void resizeEvent(QResizeEvent *event) override {
QGraphicsView::resizeEvent(event);
item2.setPixmap(qImgBin.scaled(size(), Qt::KeepAspectRatio, Qt::SmoothTransformation));
}
private:
QGraphicsPixmapItem item2;
QPixmap qImgBin;
};
// 创建自定义的QGraphicsView并设置到UI界面
MyGraphicsView1 *graphSrc = new MyGraphicsView1(&scene1);
MyGraphicsView2 *graphBin = new MyGraphicsView2(&scene2);
ui.verticalLayout->addWidget(graphSrc);
ui.verticalLayout->addWidget(graphBin);
```
上述代码中,我们创建了两个继承自`QGraphicsView`的子类`MyGraphicsView1`和`MyGraphicsView2`,并重写了`resizeEvent`方法。在方法中,我们先调用父类的`resizeEvent`方法,再通过调用`setPixmap`方法设置图片的大小,使其与控件大小保持一致,并保持图片的长宽比例不变。
最后,我们将自定义的`MyGraphicsView1`和`MyGraphicsView2`添加到UI界面中。注意,我们需要将`QGraphicsPixmapItem`对象作为`MyGraphicsView1`和`MyGraphicsView2`的成员变量来进行访问。
阅读全文