简体   繁体   中英

How to print in a QDialog the output of a function? With pyqt

I have a problem displaying the output of a function in a qdialog of pyqt.

My code is as follows:

import sys
import os
import glob
import shutil
import json
import datetime
import time
import requests
from multiprocessing import Queue

start_time = time.time()

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QPushButton, QLabel, QScrollArea, QProgressBar, QTextEdit

noreports = len(glob.glob('*.txt'))

class Dialogo(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.resize(400, 380)
        self.nombre = QLabel(self)
        self.nombre.setGeometry(QtCore.QRect(30, 20, 171, 17))
        self.nombre.setObjectName("nombre")
        self.label = QLabel(self)
        self.label.setGeometry(QtCore.QRect(30, 50, 121, 17))
        self.label.setObjectName("label")
        self.pushButton = QPushButton(self)
        self.pushButton.setGeometry(QtCore.QRect(260, 310, 86, 28))
        self.pushButton.setObjectName("pushButton")
        self.scrollArea = QScrollArea(self)
        self.scrollArea.setGeometry(QtCore.QRect(30, 120, 341, 171))
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 337, 167))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.progressBar = QProgressBar(self)
        self.progressBar.setGeometry(QtCore.QRect(30, 80, 341, 23))
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName("progressBar")
        self.textEdit = QTextEdit(self)
        self.scrollArea.setWidget(self.textEdit)

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

    def retranslateUi(self, Dialogo):
        global noreports
        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate("Dialog", "Process..."))
        self.label.setText(_translate("Dialog", "Files:" + str(noreports)))
        self.pushButton.setText(_translate("Dialog", "Terminate"))

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(321, 247)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("../../../../api-server/favicon.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        Form.setWindowIcon(icon)
        Form.setWindowOpacity(0.98)
        Form.setProperty("sunrise", QtGui.QPixmap("../../../../api-server/ejemplo.png"))
        self.lineEdit = QtWidgets.QLineEdit(Form)
        self.lineEdit.setGeometry(QtCore.QRect(20, 130, 281, 51))
        self.lineEdit.setAutoFillBackground(True)
        self.lineEdit.setObjectName("lineEdit")
        self.DescriptLbl = QtWidgets.QLabel(Form)
        self.DescriptLbl.setGeometry(QtCore.QRect(20, 100, 281, 20))
        self.DescriptLbl.setObjectName("DescriptLbl")
        self.showinformBtn = QtWidgets.QPushButton(Form)
        self.showinformBtn.setGeometry(QtCore.QRect(30, 190, 161, 31))
        self.showinformBtn.setStyleSheet("background:rgb(110, 175, 255);\n"
"color:rgb(36, 36, 36);\n"
"border-radius:3px;\n"
"border-color:black;")
        self.showinformBtn.setObjectName("showinformBtn")
        self.dialogo = Dialogo()
        self.showinformBtn.clicked.connect(self.abrirDialogo)
        #self.showinformBtn.clicked.connect(self.showinform)
        self.CancelarBtn = QtWidgets.QPushButton(Form)
        self.CancelarBtn.setGeometry(QtCore.QRect(220, 190, 75, 31))
        self.CancelarBtn.setStyleSheet("background:rgb(226, 76, 31);\n"
"color:rgb(36, 36, 36);\n"
"border-radius:3px;\n"
"border-color:black;")
        self.CancelarBtn.setObjectName("CancelarBtn")
        self.label_2 = QtWidgets.QLabel(Form)
        self.label_2.setGeometry(QtCore.QRect(20, 220, 311, 20))
        self.label_2.setTextFormat(QtCore.Qt.RichText)
        self.label_2.setScaledContents(True)
        self.label_2.setOpenExternalLinks(True)
        self.label_2.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByKeyboard|QtCore.Qt.LinksAccessibleByMouse|QtCore.Qt.TextBrowserInteraction|QtCore.Qt.TextEditable|QtCore.Qt.TextEditorInteraction|QtCore.Qt.TextSelectableByKeyboard|QtCore.Qt.TextSelectableByMouse)
        self.label_2.setObjectName("label_2")
        self.showinformLbl = QtWidgets.QLabel(Form)
        self.showinformLbl.setGeometry(QtCore.QRect(20, 30, 281, 41))
        font = QtGui.QFont()
        font.setPointSize(22)
        self.showinformLbl.setFont(font)
        self.showinformLbl.setObjectName("showinformLbl")
        self.imagen = QtWidgets.QLabel(Form)
        self.imagen.setGeometry(QtCore.QRect(-80, 0, 221, 231))
        self.imagen.setText("")
        self.imagen.setPixmap(QtGui.QPixmap("max.png"))
        self.imagen.setScaledContents(False)
        self.imagen.setIndent(-1)
        self.imagen.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
        self.imagen.setObjectName("imagen")
        self.imagen.raise_()
        self.lineEdit.raise_()
        self.DescriptLbl.raise_()
        self.showinformBtn.raise_()
        self.CancelarBtn.raise_()
        self.label_2.raise_()
        self.showinformLbl.raise_()

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

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "api-server"))
        self.lineEdit.setToolTip(_translate("Form", "<html><head/><body><p>write.</p></body></html>"))
        self.lineEdit.setWhatsThis(_translate("Form", "<html><head/><body><p>write.</p></body></html>"))
        self.DescriptLbl.setText(_translate("Form", "descrip inform."))
        self.showinformBtn.setToolTip(_translate("Form", "<html><head/><body><p>Create report.</p></body></html>"))
        self.showinformBtn.setText(_translate("Form", "show inform"))
        self.CancelarBtn.setToolTip(_translate("Form", "<html><head/><body><p>Cancel.</p></body></html>"))
        self.CancelarBtn.setText(_translate("Form", "Cancel"))
        self.label_2.setText(_translate("Form", "<html><head/><body><p>Visit api-server.  ;)</p></body></html>"))
        self.showinformLbl.setText(_translate("Form", "show inform."))

    def abrirDialogo(self):
        nombreinform = self.lineEdit.text()
        self.dialogo.nombre.setText('inform:' + nombreinform)
        self.dialogo.show()
        self.showinform()

    def showinform(self):
        current_time = datetime.datetime.today().strftime("%Y-%b-%dT%H_%M")

        alle = glob.glob('*.txt')
        counterfile = noreports
        porcentotal = 0
        suma = 100/counterfile
        counterbien = 0
        for file in alle:
            porcentotal += float(suma)
            avance = round(float(porcentotal), 0)
            self.dialogo.progressBar.setProperty("value", format(avance))
            self.dialogo.textEdit.setText(file + format(avance))
            print ('{!r} %'.format(avance))
            dict = '{!r} %'.format(avance)
            f = open(file,'w')
            f.write('result = ' + repr(dict) + '\n')


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

The code is executed but not displayed in Dialog, only the labels but not the progress bar.

Why does this happen?

The problem is that you are using the format function badly, this is used when you have a string and you want to insert data with a certain format.

The setProperty function requires as first parameter the property you want to assign, and a second value of the type that requires the property, in your case value requires an integer value so you can pass the percentage directly without needing to change it to string.

If you read many files this can block the main thread where the GUI is drawn, to solve this you must use QApplication.processEvents()

def showinform(self):
    current_time = datetime.datetime.today().strftime("%Y-%b-%dT%H_%M")

    alle = glob.glob('*.txt')
    counterfile = noreports
    porcentotal = 0
    suma = 100/counterfile
    counterbien = 0
    for file in alle:
        porcentotal += float(suma)
        avance = round(float(porcentotal), 0)
        self.dialogo.progressBar.setProperty("value", avance)
        self.dialogo.textEdit.append("{}{}".format(file, avance))
        print ('{!r} %'.format(avance))
        dict = '{!r} %'.format(avance)
        QApplication.processEvents()
        f = open(file,'w')
        f.write('result = ' + repr(dict) + '\n')

Note: I have changed the setText function to append in QTextEdit so that it is added and not overwritten.

Instead of using setProperty you could use the setValue function of QProgressBar :

self.dialogo.progressBar.setValue(avance)

Another recommendation is to verify that the counterfile is non-zero since it could generate an exception for the division.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM