为什么发射和信号在同一类中不起作用?

时间:2019-01-20 22:16:32

标签: python pyqt pyqt5

我是一个初学者,我检查了一些有关信号和插槽的教程以及许多示例。我不明白为什么我会不断收到有关全局变量和局部变量的错误。请告诉我我在做什么错!这可能是一个简单的错误,我似乎找不到!我正在尝试使用Qgraphicsview发出将在mousePressevent上显示的图片坐标,而我无法设法将其连接到QGraphicsView,所以当我单击图像时我会收到QLineEdit中显示的图像坐标。先感谢您!这是代码:

import sys
from cv2 import cv2
from PyQt5 import QtCore
from PyQt5.QtCore import pyqtSlot, QPoint, pyqtSignal
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QMainWindow, QApplication, QFileDialog, QGraphicsScene, QGraphicsPixmapItem, QGraphicsView
from PyQt5.uic import loadUi

class ImageLab(QMainWindow):

    photoClicked = pyqtSignal(QPoint)
    def __init__(self):
        super(ImageLab, self).__init__()
        loadUi("image_Lab4.ui", self)
        self.image = None
        self.actionload.triggered.connect(self.load_image)
        self.actionsave.triggered.connect(self.save_image)
        self.graphicsView.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        self.graphicsView.setResizeAnchor(QGraphicsView.AnchorUnderMouse)
        self.graphicsView.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.graphicsView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.graphicsView.photoClicked.connect(self.photoclicked)

    @pyqtSlot()
    def load_image(self):

        f_name, filter = QFileDialog.getOpenFileName(self, "Open File", "", "Image Files (*.png *.jpg *.bmp)")
        if f_name:
            self.loadImage(f_name)
        else:
            print("You canceled")

    @pyqtSlot()
    def save_image(self):

        if self.image is None:
            self.show_message("Help", "Load an Image")
            return
        f_name, filter = QFileDialog.getSaveFileName(self, "Save File", "", "Image Files (*.png *.jpg *.bmp)")
        if f_name:
            cv2.imwrite(f_name, self.image)
        else:
            print("You canceled")

    def loadImage(self, f_name):
        self.image = cv2.imread(f_name, cv2.IMREAD_ANYCOLOR)
        self.displayImage()

    def displayImage(self):
        qformat = QImage.Format_Indexed8
        if len(self.image.shape) == 3:
            if (self.image.shape[2]) == 4:
                qformat = QImage.Format_RGBA8888
            else:
                qformat = QImage.Format_RGB888
        img = QImage(self.image,
                     self.image.shape[1], self.image.shape[0], self.image.strides[0],
                     qformat)
        img = img.rgbSwapped()
        img = img.scaled(self.size(), QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)
        self.pixmap = QGraphicsPixmapItem(QPixmap.fromImage(img))
        self.scene = QGraphicsScene(self)
        self.scene.addItem(self.pixmap)
        self.graphicsView.setScene(self.scene)

    def mousePressEvent(self, event):

        if self.pixmap.isUnderMouse():
            p = self.pixmap.mapToItem(self.pixmap, self.graphicsView.mapToScene(event.pos()))
            self.graphicsView.photoClicked.emit(p.toPoint())
        super(ImageLab, self).mousePressEvent(event)

    @pyqtSlot()
    def photoclicked(self, pos):
        self.lineEdit.setText('%d, %d' % (pos.x(), pos.y()))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ImageLab()
    window.setWindowTitle("Image_Lab")
    window.show()
    sys.exit(app.exec_())

以下是错误:

    File "/anaconda3/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 3267, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-2-cdac41bb928c>", line 1, in <module>
runfile('/Users/et/PycharmProjects/project/Try1.py', wdir='/Users/et/PycharmProjects/project')
File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_bundle/pydev_umd.py", line 198, in runfile
pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
File "/Applications/PyCharm.app/Contents/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/Users/et/PycharmProjects/project/Try1.py", line 79, in <module>
window = ImageLab()
File "/Users/et/PycharmProjects/project/Try1.py", line 22, in __init__
self.graphicsView.photoClicked.connect(self.photoclicked)
AttributeError: 'QGraphicsView' object has no attribute 'photoClicked'

.ui文件在这里:

    # -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'image_Lab4.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setWindowModality(QtCore.Qt.ApplicationModal)
        MainWindow.resize(825, 661)
        MainWindow.setMinimumSize(QtCore.QSize(1, 1))
        MainWindow.setMaximumSize(QtCore.QSize(1800, 1200))
        MainWindow.setAcceptDrops(False)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("IconsImagelab/Mainicon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        MainWindow.setWindowIcon(icon)
        MainWindow.setLayoutDirection(QtCore.Qt.LeftToRight)
        MainWindow.setAutoFillBackground(False)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)
        self.graphicsView.setEnabled(True)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.graphicsView.sizePolicy().hasHeightForWidth())
        self.graphicsView.setSizePolicy(sizePolicy)
        palette = QtGui.QPalette()
        brush = QtGui.QBrush(QtGui.QColor(64, 64, 64))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
        brush = QtGui.QBrush(QtGui.QColor(64, 64, 64))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
        brush = QtGui.QBrush(QtGui.QColor(236, 236, 236))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
        self.graphicsView.setPalette(palette)
        self.graphicsView.setMouseTracking(True)
        self.graphicsView.setAcceptDrops(True)
        self.graphicsView.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
        self.graphicsView.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
        self.graphicsView.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustIgnored)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        self.graphicsView.setBackgroundBrush(brush)
        brush = QtGui.QBrush(QtGui.QColor(0, 0, 0))
        brush.setStyle(QtCore.Qt.NoBrush)
        self.graphicsView.setForegroundBrush(brush)
        self.graphicsView.setInteractive(True)
        self.graphicsView.setSceneRect(QtCore.QRectF(0.0, 0.0, 0.0, 0.0))
        self.graphicsView.setRenderHints(QtGui.QPainter.Antialiasing|QtGui.QPainter.SmoothPixmapTransform)
        self.graphicsView.setDragMode(QtWidgets.QGraphicsView.NoDrag)
        self.graphicsView.setTransformationAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
        self.graphicsView.setResizeAnchor(QtWidgets.QGraphicsView.AnchorUnderMouse)
        self.graphicsView.setViewportUpdateMode(QtWidgets.QGraphicsView.MinimalViewportUpdate)
        self.graphicsView.setRubberBandSelectionMode(QtCore.Qt.IntersectsItemShape)
        self.graphicsView.setObjectName("graphicsView")
        self.gridLayout.addWidget(self.graphicsView, 1, 1, 1, 1)
        self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit.setReadOnly(True)
        self.lineEdit.setObjectName("lineEdit")
        self.gridLayout.addWidget(self.lineEdit, 2, 1, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 825, 22))
        self.menubar.setObjectName("menubar")
        self.menuMenu = QtWidgets.QMenu(self.menubar)
        self.menuMenu.setObjectName("menuMenu")
        self.menuEdit = QtWidgets.QMenu(self.menubar)
        self.menuEdit.setObjectName("menuEdit")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.toolBar = QtWidgets.QToolBar(MainWindow)
        self.toolBar.setCursor(QtGui.QCursor(QtCore.Qt.ArrowCursor))
        self.toolBar.setMovable(False)
        self.toolBar.setIconSize(QtCore.QSize(36, 36))
        self.toolBar.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
        self.toolBar.setObjectName("toolBar")
        MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
        self.actionload = QtWidgets.QAction(MainWindow)
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap("IconsImagelab/file-import-icon-10.jpg.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionload.setIcon(icon1)
        self.actionload.setObjectName("actionload")
        self.actionsave = QtWidgets.QAction(MainWindow)
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap("IconsImagelab/3floppy-mount-icon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionsave.setIcon(icon2)
        self.actionsave.setObjectName("actionsave")
        self.actionlowpass = QtWidgets.QAction(MainWindow)
        icon3 = QtGui.QIcon()
        icon3.addPixmap(QtGui.QPixmap("IconsImagelab/Actions-view-filter-icon.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.actionlowpass.setIcon(icon3)
        self.actionlowpass.setObjectName("actionlowpass")
        self.actionpixelmode = QtWidgets.QAction(MainWindow)
        self.actionpixelmode.setIcon(icon3)
        self.actionpixelmode.setObjectName("actionpixelmode")
        self.actionzoomin = QtWidgets.QAction(MainWindow)
        self.actionzoomin.setObjectName("actionzoomin")
        self.actionzoomout = QtWidgets.QAction(MainWindow)
        self.actionzoomout.setObjectName("actionzoomout")
        self.actionzoom0 = QtWidgets.QAction(MainWindow)
        self.actionzoom0.setObjectName("actionzoom0")
        self.menuMenu.addAction(self.actionload)
        self.menuMenu.addAction(self.actionsave)
        self.menuMenu.addAction(self.actionzoomin)
        self.menuMenu.addAction(self.actionzoomout)
        self.menuMenu.addAction(self.actionzoom0)
        self.menuEdit.addAction(self.actionlowpass)
        self.menuEdit.addAction(self.actionpixelmode)
        self.menubar.addAction(self.menuMenu.menuAction())
        self.menubar.addAction(self.menuEdit.menuAction())
        self.toolBar.addAction(self.actionload)
        self.toolBar.addAction(self.actionsave)
        self.toolBar.addAction(self.actionlowpass)
        self.toolBar.addAction(self.actionpixelmode)
        self.toolBar.addAction(self.actionzoomin)
        self.toolBar.addAction(self.actionzoomout)
        self.toolBar.addAction(self.actionzoom0)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.menuMenu.setTitle(_translate("MainWindow", "File"))
        self.menuEdit.setTitle(_translate("MainWindow", "Edit"))
        self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar"))
        self.actionload.setText(_translate("MainWindow", "Open"))
        self.actionload.setToolTip(_translate("MainWindow", "Click to load"))
        self.actionload.setStatusTip(_translate("MainWindow", "Loads an image"))
        self.actionsave.setText(_translate("MainWindow", "Save"))
        self.actionsave.setToolTip(_translate("MainWindow", "Click to save"))
        self.actionsave.setStatusTip(_translate("MainWindow", "Saves the image"))
        self.actionlowpass.setText(_translate("MainWindow", "Lowpass"))
        self.actionlowpass.setToolTip(_translate("MainWindow", "Click to filter"))
        self.actionlowpass.setStatusTip(_translate("MainWindow", "Applies low-pass filter"))
        self.actionpixelmode.setText(_translate("MainWindow", "Highpass"))
        self.actionpixelmode.setIconText(_translate("MainWindow", "Highpass"))
        self.actionpixelmode.setToolTip(_translate("MainWindow", "Click to filter"))
        self.actionpixelmode.setStatusTip(_translate("MainWindow", "Applies high-pass filter"))
        self.actionzoomin.setText(_translate("MainWindow", "zoom in"))
        self.actionzoomout.setText(_translate("MainWindow", "zoom out"))
        self.actionzoom0.setText(_translate("MainWindow", "zoom 0 "))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

0 个答案:

没有答案