PySide2 在询问时不更新 QLabel 文本

Ubu*_*ist 2 python-3.6 pyside2 macos-high-sierra

我正在从 Python 2.7 升级到 Python 3.6,并从 PySide 升级到 PySide2。我首先尝试从“入门”站点 ( https://doc-snapshots.qt.io/qtforpython/gettingstarted.html )获取“Hello World” 。它显示小部件、其标签和按钮,但按钮不会更改标签的文本。我添加了一个 print() 来验证按钮确实调用了与点击信号关联的方法,甚至添加了一个 update() 来尝试更多地“鼓励”它。没运气。

#!/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_())
Run Code Online (Sandbox Code Playgroud)

用 pipenv 安装。而且,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"
Run Code Online (Sandbox Code Playgroud)

小智 7

在我的Mac上python3.6下通过调整magic函数修复了这个问题:

def magic(self):
    self.text.setText(random.choice(self.hello))
    self.repaint()
Run Code Online (Sandbox Code Playgroud)

由于某种原因需要 self.repaint() ,但至少有效。