pyqt5 хочет получить возвращаемое значение из диалога, вызов которого из окна виджета - PullRequest
0 голосов
/ 29 апреля 2020

все страницы генерируются из QT Designer в python код. Это моя первая страница

from PyQt5 import QtCore, QtGui, QtWidgets
from DegradeUI import Ui_degradeWindow
from RestoreUI import Ui_restoreWindow
import sys

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(682, 269)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.degradationBtn = QtWidgets.QPushButton(self.centralwidget)
        self.degradationBtn.setGeometry(QtCore.QRect(140, 120, 131, 61))
        font = QtGui.QFont()
        font.setPointSize(15)
        self.degradationBtn.setFont(font)
        self.degradationBtn.setObjectName("degradationBtn")
        self.degradationBtn.clicked.connect(self.openDegrade)
        self.restorationBtn = QtWidgets.QPushButton(self.centralwidget)
        self.restorationBtn.setGeometry(QtCore.QRect(390, 120, 131, 61))
        font = QtGui.QFont()
        font.setPointSize(15)
        self.restorationBtn.setFont(font)
        self.restorationBtn.setObjectName("restorationBtn")
        self.restorationBtn.clicked.connect(self.openRestore)
        self.titleName = QtWidgets.QLabel(self.centralwidget)
        self.titleName.setGeometry(QtCore.QRect(130, 0, 401, 121))
        font = QtGui.QFont()
        font.setPointSize(15)
        font.setBold(True)
        font.setWeight(75)
        self.titleName.setFont(font)
        self.titleName.setAlignment(QtCore.Qt.AlignCenter)
        self.titleName.setObjectName("titleName")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 682, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

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

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Degradation and Resotration Program"))
        self.degradationBtn.setText(_translate("MainWindow", "Degradation"))
        self.restorationBtn.setText(_translate("MainWindow", "Restoration"))
        self.titleName.setText(_translate("MainWindow", "Degradation and Resotration Program"))

    def openDegrade(self):
        self.window = QtWidgets.QWidget()
        self.ui = Ui_degradeWindow()
        self.ui.setupUi(self.window)
        self.window.show()

    def openRestore(self):
        self.window = QtWidgets.QWidget()
        self.ui = Ui_restoreWindow()
        self.ui.setupUi(self.window)
        self.window.show()

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

при нажатии кнопки ухудшения качества будет отображаться окно виджета ухудшения

from PyQt5 import QtCore, QtGui, QtWidgets
from os.path import expanduser
import os
from degradeParam01GaussianBlurDialog import Ui_gaussianBlurDialog
import sys

class Ui_degradeWindow(object):
    def setupUi(self, degradeWindow):
        degradeWindow.setObjectName("degradeWindow")
        degradeWindow.resize(1200, 601)
        self.currentDegradeWindow = degradeWindow
        self.verticalLayoutWidget = QtWidgets.QWidget(degradeWindow)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 430, 160, 111))
        self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setObjectName("verticalLayout")
        self.GaussianBlurBtn = QtWidgets.QRadioButton(self.verticalLayoutWidget)
        self.GaussianBlurBtn.setObjectName("GaussianBlurBtn")
        self.GaussianBlurBtn.setChecked(True)
        self.verticalLayout.addWidget(self.GaussianBlurBtn)
        self.medianBlurBtn = QtWidgets.QRadioButton(self.verticalLayoutWidget)
        self.medianBlurBtn.setObjectName("medianBlurBtn")
        self.verticalLayout.addWidget(self.medianBlurBtn)
        self.gaussianNoiseBtn = QtWidgets.QRadioButton(self.verticalLayoutWidget)
        self.gaussianNoiseBtn.setObjectName("gaussianNoiseBtn")
        self.verticalLayout.addWidget(self.gaussianNoiseBtn)
        self.saltAndPepperBtn = QtWidgets.QRadioButton(self.verticalLayoutWidget)
        self.saltAndPepperBtn.setObjectName("saltAndPepperBtn")
        self.verticalLayout.addWidget(self.saltAndPepperBtn)
        self.editParamBtn = QtWidgets.QPushButton(degradeWindow)
        self.editParamBtn.setGeometry(QtCore.QRect(40, 550, 91, 31))
        self.editParamBtn.setObjectName("editParamBtn")
        self.degradeThis = QtWidgets.QPushButton(degradeWindow)
        self.degradeThis.setGeometry(QtCore.QRect(230, 520, 91, 41))
        self.degradeThis.setObjectName("degradeThis")
        self.degradeAll = QtWidgets.QPushButton(degradeWindow)
        self.degradeAll.setGeometry(QtCore.QRect(350, 520, 91, 41))
        self.degradeAll.setObjectName("degradeAll")
        self.origLabel = QtWidgets.QLabel(degradeWindow)
        self.origLabel.setGeometry(QtCore.QRect(320, 40, 211, 41))
        font = QtGui.QFont()
        font.setPointSize(24)
        self.origLabel.setFont(font)
        self.origLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.origLabel.setObjectName("origLabel")
        self.degradeLabel = QtWidgets.QLabel(degradeWindow)
        self.degradeLabel.setGeometry(QtCore.QRect(810, 40, 211, 41))
        font = QtGui.QFont()
        font.setPointSize(24)
        self.degradeLabel.setFont(font)
        self.degradeLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.degradeLabel.setObjectName("degradeLabel")
        self.selectFolderBtn = QtWidgets.QPushButton(degradeWindow)
        self.selectFolderBtn.setGeometry(QtCore.QRect(10, 50, 201, 31))
        font = QtGui.QFont()
        font.setPointSize(13)
        self.selectFolderBtn.setFont(font)
        self.selectFolderBtn.setObjectName("selectFolderBtn")
        self.imageList = QtWidgets.QListWidget(degradeWindow)
        self.imageList.setGeometry(QtCore.QRect(10, 90, 201, 331))
        self.imageList.setObjectName("imageList")
        self.originalImage = QtWidgets.QLabel(degradeWindow)
        self.originalImage.setGeometry(QtCore.QRect(240, 90, 421, 401))
        self.originalImage.setText("")
        self.originalImage.setTextFormat(QtCore.Qt.AutoText)
        self.originalImage.setPixmap(QtGui.QPixmap(""))
        self.originalImage.setScaledContents(False)
        self.originalImage.setAlignment(QtCore.Qt.AlignCenter)
        self.originalImage.setWordWrap(False)
        self.originalImage.setObjectName("originalImage")
        self.degradeImage = QtWidgets.QLabel(degradeWindow)
        self.degradeImage.setGeometry(QtCore.QRect(720, 90, 421, 401))
        self.degradeImage.setText("")
        self.degradeImage.setTextFormat(QtCore.Qt.AutoText)
        self.degradeImage.setPixmap(QtGui.QPixmap(""))
        self.degradeImage.setScaledContents(False)
        self.degradeImage.setAlignment(QtCore.Qt.AlignCenter)
        self.degradeImage.setWordWrap(False)
        self.degradeImage.setObjectName("degradeImage")

        #event handler
        self.selectFolderBtn.clicked.connect(self.selectFolder)
        self.imageList.itemClicked.connect(self.selectionChanged)
        self.degradeThis.clicked.connect(self.degradeThisImg)
        self.editParamBtn.clicked.connect(self.editParam)
        #declare var
        self.rootDir = ''
        self.selectedImg = None

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

    def retranslateUi(self, degradeWindow):
        _translate = QtCore.QCoreApplication.translate
        degradeWindow.setWindowTitle(_translate("degradeWindow", "Form"))
        self.GaussianBlurBtn.setText(_translate("degradeWindow", "Gaussian Blur"))
        self.medianBlurBtn.setText(_translate("degradeWindow", "Median Blur"))
        self.gaussianNoiseBtn.setText(_translate("degradeWindow", "Gaussian Noise"))
        self.saltAndPepperBtn.setText(_translate("degradeWindow", "Salt and Pepper Noise"))
        self.editParamBtn.setText(_translate("degradeWindow", "Edit Parameter"))
        self.degradeThis.setText(_translate("degradeWindow", "Degrade this"))
        self.degradeAll.setText(_translate("degradeWindow", "Degrade all"))
        self.origLabel.setText(_translate("degradeWindow", "Original"))
        self.degradeLabel.setText(_translate("degradeWindow", "Degrade"))
        self.selectFolderBtn.setText(_translate("degradeWindow", "Select Folder"))

    def selectFolder(self, degradeWindow):
        print("selectFolder")
        input_dir = QtWidgets.QFileDialog.getExistingDirectory(None, 'Select images folder', expanduser("~"))
        #print(os.getcwd())
        #input_dir = QtWidgets.QFileDialog.getOpenFileNames(None,'',filter="Images (*.png *.xpm *.jpg)")
        #print(input_dir)
        if input_dir != '':
            self.rootDir = input_dir
            self.imageList.clear()
            for i in os.listdir(input_dir):
                if(i.endswith(('.png','jpg','jpeg','jiff'))):
                    #print(i)
                    self.imageList.addItem(i)

    def selectionChanged(self,item):
        #print('select',item.text())
        #print('dir:{}'.format(os.path.join(self.rootDir,item.text())))
        self.originalImage.setPixmap(
            QtGui.QPixmap(
                "{}".format(os.path.join(self.rootDir,item.text()))
                ).scaled(self.originalImage.width(), self.originalImage.height(), QtCore.Qt.KeepAspectRatioByExpanding))
        self.selectedImg = os.path.join(self.rootDir,item.text())
        #print("Selected items: ", self.listWidget.selectedItems())

    def selectDegradeMethod(self):
        if self.GaussianBlurBtn.isChecked():
            print("use gaussian blur")
            kernel =  self.kernelSizeParam.text()
            sd = self.sdParam.text()
            print(kernel,sd)
        elif self.medianBlurBtn.isChecked():
            print("use median blur")
        elif self.saltAndPepperBtn.isChecked():
            print("use salt and pepper")
        elif self.gaussianNoiseBtn.isChecked():
            print("use gaussian noise")

    def degradeThisImg(self):
        if self.selectedImg == None:
            print('please select an image')
            self.alertNotSelectImg()
        else:
            print('degrade this image',self.selectedImg)
            self.selectDegradeMethod()

    def alertNotSelectImg(self):
        QtWidgets.QMessageBox.warning(self.currentDegradeWindow, "Error", "import or select an image")

    def editParam(self):
        if self.GaussianBlurBtn.isChecked():
            gaussianBlurDialog = QtWidgets.QDialog()
            ui = Ui_gaussianBlurDialog()
            ui.setupUi(gaussianBlurDialog)
            res = gaussianBlurDialog.exec_()
            print(res.returnValue())
            # if gaussianBlurDialog.result() == 1:
            #     print("set new param")
            #     #value1,value2 = res.returnValue()
            # else:
            #     print("use old param")

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    degradeWindow = QtWidgets.QWidget()
    ui = Ui_degradeWindow()
    ui.setupUi(degradeWindow)
    degradeWindow.show()
    sys.exit(app.exec_())

при нажатии кнопки редактирования. Кнопка Param, она покажет диалог с полем ввода для пользователя, чтобы ввести новое значение. затем нажмите ОК. Я хочу сохранить значение из этого диалогового окна в виджете деградации. Это мой диалог

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_gaussianBlurDialog(object):
    def setupUi(self, gaussianBlurDialog):
        gaussianBlurDialog.setObjectName("gaussianBlurDialog")
        self.currentForm = gaussianBlurDialog
        gaussianBlurDialog.resize(358, 175)
        self.buttonBox = QtWidgets.QDialogButtonBox(gaussianBlurDialog)
        self.buttonBox.setGeometry(QtCore.QRect(-90, 130, 341, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.kernelLabel = QtWidgets.QLabel(gaussianBlurDialog)
        self.kernelLabel.setGeometry(QtCore.QRect(70, 60, 91, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.kernelLabel.setFont(font)
        self.kernelLabel.setObjectName("kernelLabel")
        self.kernelSizeParam = QtWidgets.QLineEdit(gaussianBlurDialog)
        self.kernelSizeParam.setGeometry(QtCore.QRect(170, 60, 113, 20))
        self.kernelSizeParam.setText("")
        self.kernelSizeParam.setObjectName("kernelSizeParam")
        self.sdLabel = QtWidgets.QLabel(gaussianBlurDialog)
        self.sdLabel.setGeometry(QtCore.QRect(120, 100, 47, 13))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.sdLabel.setFont(font)
        self.sdLabel.setObjectName("sdLabel")
        self.sdParam = QtWidgets.QLineEdit(gaussianBlurDialog)
        self.sdParam.setGeometry(QtCore.QRect(170, 100, 113, 20))
        self.sdParam.setObjectName("sdParam")
        self.titleName = QtWidgets.QLabel(gaussianBlurDialog)
        self.titleName.setGeometry(QtCore.QRect(20, 10, 311, 41))
        font = QtGui.QFont()
        font.setPointSize(20)
        self.titleName.setFont(font)
        self.titleName.setAlignment(QtCore.Qt.AlignCenter)
        self.titleName.setObjectName("titleName")

        self.retranslateUi(gaussianBlurDialog)
        #self.buttonBox.accepted.connect(gaussianBlurDialog.accept)
        self.buttonBox.accepted.connect(self.saveParam)
        self.buttonBox.rejected.connect(self.closeParam)
        self.param = []
        QtCore.QMetaObject.connectSlotsByName(gaussianBlurDialog)

    def retranslateUi(self, gaussianBlurDialog):
        _translate = QtCore.QCoreApplication.translate
        gaussianBlurDialog.setWindowTitle(_translate("gaussianBlurDialog", "Dialog"))
        self.kernelLabel.setText(_translate("gaussianBlurDialog", "Kernel size"))
        self.sdLabel.setText(_translate("gaussianBlurDialog", "S.D"))
        self.titleName.setText(_translate("gaussianBlurDialog", "Gaussian Blur parameter"))

    def saveParam(self):
        self.param.append(self.kernelSizeParam.text())
        self.param.append(self.sdParam.text())
        #self.currentForm.done(int)
        self.currentForm.accept()
        print(self.param)
        return (self.param)

    def returnValue(self):
        return self.param

    def closeParam(self):
        self.currentForm.reject()

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    gaussianBlurDialog = QtWidgets.QDialog()
    ui = Ui_gaussianBlurDialog()
    ui.setupUi(gaussianBlurDialog)
    gaussianBlurDialog.show()
    sys.exit(app.exec_())

Я попытался использовать accept () и done (). done () даст мне TypeError: done(self, int): argument 1 has unexpected type 'type'

accept () даст мне 1, что означает, что оно возвращает True right?

но как получить доступ к значению, которое я хочу?

Я пытаюсь вызвать res.param и res.returnValue (), но это не работает

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...