PySide2 not updating QLabel text when asked

2020-04-16 17:41发布

问题:

I am upgrading from Python 2.7 to Python 3.6 and from PySide to PySide2. I started by trying to get the "Hello World" from the "Getting Started" site (https://doc-snapshots.qt.io/qtforpython/gettingstarted.html) working. It displays the widget, its label and the push button, but the push button does not change the text of the label. I added a print() to verify that the button is indeed calling the method associated with the click signal, and even added an update() to try to "encourage" it a bit more. No luck.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copied from:
#   https://doc-snapshots.qt.io/qtforpython/gettingstarted.html
#
# Mac OS X High Sierra (10.13.6)
#
# Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 05:52:31) 
# [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin
#
# PySide2 5.11.1 
#

import sys
import random
from PySide2 import QtCore, QtWidgets, QtGui


class MyWidget(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()

        self.hello = ["Hallo Welt", "你好,世界", "Hei maailma",
                      "Hola Mundo", "Привет мир"]

        self.button = QtWidgets.QPushButton("Click me!")
        self.text = QtWidgets.QLabel("Hello World")
        self.text.setAlignment(QtCore.Qt.AlignCenter)

        self.text.setFont(QtGui.QFont("Titillium", 30))
        self.button.setFont(QtGui.QFont("Titillium", 20))

        self.layout = QtWidgets.QVBoxLayout()
        self.layout.addWidget(self.text)
        self.layout.addWidget(self.button)
        self.setLayout(self.layout)

        self.button.clicked.connect(self.magic)

    def magic(self):
        hi = random.choice(self.hello)
        print(hi)              # Prints when clicked
        self.text.setText(hi)  # Label text does not change when clicked
#       self.update()          # Didn't help

if __name__ == "__main__":
    app = QtWidgets.QApplication([])

    widget = MyWidget()
    widget.resize(800, 600)
    widget.show()

    sys.exit(app.exec_())

Installed with pipenv. And, the Pipfile:

[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"

[[source]]
url = "http://download.qt.io/snapshots/ci/pyside/5.11/latest"
verify_ssl = false
name = "qt5"

[packages]
pyside2 = {version="*", index="qt5"}

[dev-packages]

[requires]
python_version = "3.6"

回答1:

Fixed this problem on my Mac under python3.6 by adjusting the magic function:

def magic(self):
    self.text.setText(random.choice(self.hello))
    self.repaint()

The self.repaint() is needed for some reason, but at least works.