繁体   English   中英

无法从pyqt5访问生成的代码内的变量

[英]Can't access the variable inside the generated code from pyqt5

这是我的第一篇文章,我还要感谢Stack Overflow惊人的社区,这些年来一直为我提供帮助!

但是,经过大量研究,我找不到解决我问题的方法。 我有QtCreator生成的包含进度条的文件。 在我的代码中,我有2个类,其中1个是线程。 该线程必须更改progressbar的值,但我完全无法这样做。

我无法从我的线程访问变量,但可以从Mainwindow的初始化访问。 我认为问题出在setprogressBar中“自我”变量的本质,但我确实难以发现它是什么。

当我尝试执行此代码时,结果如下:

File "C:\test.py", line 14, in setprogressBar
self.progressBar.setProperty("value", pourcentage)
AttributeError: type object 'MainWindow' has no attribute 'progressBar'

使用QtCreator生成的文件A:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        self.progressBar = QtWidgets.QProgressBar(self.widget)
        self.progressBar.setObjectName("progressBar")

文件B,我的代码:

from PyQt5 import QtWidgets
from UImainwindow import Ui_MainWindow
from threading import Thread
import sys

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
 # access variables inside of the UI's file
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self) # gets defined in the UI file
        self.progressBar.setProperty("value", 24) #This is working

    def setprogressBar(self, pourcentage):
        self.progressBar.setProperty("value", pourcentage) #This is not

class B(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run(self):          
        MainWindow.setprogressBar(MainWindow ,48)

APP = QtWidgets.QApplication(sys.argv)

Bi = B()
Bi.start()

MAINWIN = MainWindow()
MAINWIN.show()

APP.exec_()

帮忙的家伙很多!

MainWindow是一个类,而不是一个对象。 相反,您应该做的是:

class B(Thread):
    def __init__(self, target):
        self.__target = target

    def run(self):
        self.__target.setprogressBar(48)

MAINWIN = MainWindow()

bi = B(MAINWIN)
bi.start()

MAINWIN.show()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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