pyqt5 父类窗口class Ui_MainWindow()有一个控件QGraphicsView,怎么样让子类QGraphicsView继承父类Ui_MainWindow,可以进行图片显示,放大缩小
时间: 2024-02-02 15:45:55 浏览: 33
你可以在子类中定义一个QGraphicsView控件,并且将其继承父类Ui_MainWindow中的QGraphicsView控件,然后在子类中重写一些方法来实现图片显示、放大缩小等功能。
下面是一个简单的示例代码:
```python
from PyQt5.QtWidgets import QMainWindow, QGraphicsView
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QImage, QPixmap
from ui_mainwindow import Ui_MainWindow
class MyGraphicsView(QGraphicsView):
def __init__(self, parent=None):
super(MyGraphicsView, self).__init__(parent)
self.setDragMode(QGraphicsView.ScrollHandDrag)
def set_image(self, image):
scene = self.scene()
if scene is None:
scene = QGraphicsScene(self)
self.setScene(scene)
pixmap = QPixmap.fromImage(image)
scene.clear()
scene.addPixmap(pixmap)
self.fitInView(pixmap.rect(), Qt.KeepAspectRatio)
def wheelEvent(self, event):
delta = event.angleDelta().y()
factor = 1.1 ** (delta / 240.0)
self.scale(factor, factor)
class MainWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.setupUi(self)
self.graphicsView = MyGraphicsView(self.centralwidget)
# 将子类的graphicsView控件继承父类的graphicsView控件
self.graphicsView.setObjectName("graphicsView")
self.gridLayout.addWidget(self.graphicsView, 0, 0, 1, 1)
def show_image(self, image_path):
image = QImage(image_path)
self.graphicsView.set_image(image)
```
在这个示例中,我们定义了一个子类`MyGraphicsView`,它继承了父类`Ui_MainWindow`中的`QGraphicsView`控件,并且重写了`set_image`方法和`wheelEvent`方法实现了图片显示、放大缩小等功能。在`MainWindow`类中,我们将子类`MyGraphicsView`的对象作为父类`Ui_MainWindow`中的`QGraphicsView`控件来使用,这样就可以直接调用`set_image`方法来显示图片,并且可以通过`wheelEvent`方法实现放大缩小功能。
你可以参考这个示例代码,在自己的项目中进行修改和使用。