我正在从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_())
用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"
通过调整魔术函数修复了python3.6下我的Mac上的这个问题:
def magic(self):
self.text.setText(random.choice(self.hello))
self.repaint()
self.repaint()由于某种原因需要,但至少有效。