gpt4 book ai didi

python-3.6 - PySide2 在被询问时不更新 QLabel 文本

转载 作者:行者123 更新时间:2023-12-03 16:49:46 24 4
gpt4 key购买 nike

我正在从 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"

最佳答案

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

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

出于某种原因需要 self.repaint(),但至少可以工作。

关于python-3.6 - PySide2 在被询问时不更新 QLabel 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51601213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com