Как показать растровое изображение в pyqt5 в __init__ - PullRequest
0 голосов
/ 02 октября 2019

У меня есть простое приложение Python, использующее PyQt5, которое должно выполнить обновление. В настоящее время я застрял непосредственно в __init__, когда я добавляю два растровых изображения и lineEdit, текст которого я хочу обновить во время вычисления.

При каждом использовании main_window.change() графический интерфейс не отображается доизменение () завершено.

Картинки не отображаются.

Без метода изменения отображаются фотографии

Без измененияGUI метода отображается правильно

Если я добавлю QMessageBox в цикл for, сообщение, конечно же, будет показано, но обновленный GUI станет видимым.

Окно сообщения обновляет графический интерфейс

Добавление self.update() не помогло.

class AcselStarter(QtWidgets.QMainWindow, Ui_ACSEL_Starter):

    def __init__(self, parent=None):

        super(AcselStarter, self).__init__(parent)
        Ui_ACSEL_Starter.__init__(self)
        self.setupUi(self)

        pixmapAcsel = QPixmap('../fig/ACSEL.png')
        self.labelAcsel.setPixmap(pixmapAcsel)

        pixmapMubea = QPixmap('../fig/CAELogo_height60.png')
        self.labelMubea.setPixmap(pixmapMubea)

        self.lineEditProgress.setText(str(0.001))

    def change(self):
        for i in range(0, 100, 10):
            self.lineEditProgress.setText(str(i))
            # QtWidgets.QMessageBox.information(self, PROGRAMM_NAME, 'Replot', QtWidgets.QMessageBox.Ok)



if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)

    main_window = AcselStarter()
    main_window.show()
    time.sleep(5)
    main_window.change()

    sys.exit(app.exec_())

Для полноты, вот мой файл UI от Qt Designer:

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

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

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_ACSEL_Starter(object):
    def setupUi(self, ACSEL_Starter):
        ACSEL_Starter.setObjectName("ACSEL_Starter")
        ACSEL_Starter.resize(320, 180)
        self.centralwidget = QtWidgets.QWidget(ACSEL_Starter)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.widgetPics = QtWidgets.QWidget(self.centralwidget)
        self.widgetPics.setObjectName("widgetPics")
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.widgetPics)
        self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.labelAcsel = QtWidgets.QLabel(self.widgetPics)
        self.labelAcsel.setText("")
        self.labelAcsel.setObjectName("labelAcsel")
        self.horizontalLayout_2.addWidget(self.labelAcsel)
        self.labelMubea = QtWidgets.QLabel(self.widgetPics)
        self.labelMubea.setText("")
        self.labelMubea.setObjectName("labelMubea")
        self.horizontalLayout_2.addWidget(self.labelMubea)
        self.gridLayout.addWidget(self.widgetPics, 0, 0, 1, 1)
        self.widgetProgress = QtWidgets.QWidget(self.centralwidget)
        self.widgetProgress.setMaximumSize(QtCore.QSize(16777215, 30))
        self.widgetProgress.setObjectName("widgetProgress")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.widgetProgress)
        self.horizontalLayout.setSizeConstraint(QtWidgets.QLayout.SetFixedSize)
        self.horizontalLayout.setContentsMargins(0, 9, 0, 0)
        self.horizontalLayout.setSpacing(6)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.labelProgress = QtWidgets.QLabel(self.widgetProgress)
        self.labelProgress.setMaximumSize(QtCore.QSize(48, 16777215))
        self.labelProgress.setObjectName("labelProgress")
        self.horizontalLayout.addWidget(self.labelProgress)
        self.lineEditProgress = QtWidgets.QLineEdit(self.widgetProgress)
        self.lineEditProgress.setMaximumSize(QtCore.QSize(50, 16777215))
        self.lineEditProgress.setObjectName("lineEditProgress")
        self.horizontalLayout.addWidget(self.lineEditProgress)
        self.labelPercent = QtWidgets.QLabel(self.widgetProgress)
        self.labelPercent.setObjectName("labelPercent")
        self.horizontalLayout.addWidget(self.labelPercent)
        self.gridLayout.addWidget(self.widgetProgress, 1, 0, 1, 1)
        ACSEL_Starter.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(ACSEL_Starter)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 320, 21))
        self.menubar.setObjectName("menubar")
        ACSEL_Starter.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(ACSEL_Starter)
        self.statusbar.setObjectName("statusbar")
        ACSEL_Starter.setStatusBar(self.statusbar)

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

    def retranslateUi(self, ACSEL_Starter):
        _translate = QtCore.QCoreApplication.translate
        ACSEL_Starter.setWindowTitle(_translate("ACSEL_Starter", "ACSEL_Starter"))
        self.labelProgress.setText(_translate("ACSEL_Starter", "Progress"))
        self.labelPercent.setText(_translate("ACSEL_Starter", "%"))


Я ожидаю, что графический интерфейс будет обновляться всякий раз, когда я устанавливаю новый текст в lineEdit.

Заранее благодарю за помощь!

1 Ответ

0 голосов
/ 07 октября 2019

Я только что нашел решение самостоятельно и использовал лучший индикатор выполнения вместо lineEdit. Здесь решение, когда индикатор выполнения активируется с помощью кода, а не кнопки Click. Потому что тогда новый поток должен быть выполнен вручную. ButtonClick делает это автоматически внутри.

class ThreadClass(QThread):
    valChanged = pyqtSignal(int)

    def run(self):
        print('run thread')  # e.g. file download
        count = 0
        while count < 100:
            count += 0.0005
            self.valChanged.emit(count)
        print('finished thread')

        main_window.my_property = True
        self.quit()


class AcselStarter_Thread(QtWidgets.QMainWindow, Ui_ACSEL_Starter):
    """
    Activating the progress bar within the code without ButtonClick is not working.
    """

    def __init__(self, parent=None):
        super(AcselStarter_Thread, self).__init__(parent)
        Ui_ACSEL_Starter.__init__(self)
        self.setupUi(self)

        pixmapAcsel = QPixmap('../fig/ACSEL.png')
        self.labelAcsel.setPixmap(pixmapAcsel)

        pixmapMubea = QPixmap('../fig/CAELogo_height60.png')
        self.labelMubea.setPixmap(pixmapMubea)

        self.progressBar.setMaximum(100)
        self.progressBar.setValue(0)

        self.__my_property = False

    @property
    def my_property(self):
        return self.__my_property

    @my_property.setter
    def my_property(self, val):
        self.__my_property = val
        print('new val')

        if self.__my_property:
            self.do_something_after_progressbar()

    def update_progressbar(self, val):
        self.progressBar.setValue(val)

    def do_thread(self):
        # e.g. file update/download
        print('do_thread')
        self.threadClass = ThreadClass()
        self.threadClass.valChanged.connect(self.update_progressbar)
        self.threadClass.start()

    def do_something_after_progressbar(self):
        # e.g. moving the downloaded files and starting the updated app
        print('do_something_after_progressbar')


if __name__ == '__main__':
    """
    Main method. Starts the application
    __name__ ==  '__main__' is true, if this file is run directly and not imported.
    """

    app = QtWidgets.QApplication(sys.argv)

    main_window = AcselStarter_Thread()
    main_window.show()
    main_window.do_thread()

    sys.exit(app.exec_())

Вывод следующий, как ожидалось / хотел:

do_thread
run thread
finished thread
new val
do_something_after_progressbar
...