[英]Issue about PyQt5
我正在尝试创建一个像这样的简单界面:
from PyQt5 import QtWidgets,QtGui
class program():
def __init__(self):
self.window = QtWidgets.QWidget()
self.window.setWindowTitle("how many click")
self.text = QtWidgets.QLabel(self.window)
self.text.setText(("not clicked"))
self.text.setGeometry(240,200,300,50)
self.text2 = QtWidgets.QLabel(self.window)
self.picture = QtWidgets.QLabel(self.window)
self.button=QtWidgets.QPushButton(self.window)
self.button.setText("click")
self.button.setFont(QtGui.QFont('',10))
self.button.setGeometry(250,100,200,50)
self.window.setGeometry(600,200,800,600)
self.window.show()
self.count=0
self.button.clicked.connect(self.click)
def click(self):
self.count+= 1
self.text.setText(((f"you clicked {self.count} times")))
self.text.setFont(QtGui.QFont('',10))
if self.count == 5:
self.text2.setText(("You clicked too much"))
self.text2.setGeometry(250, 250, 300, 50)
self.picture.setPixmap(QtGui.QPixmap("C:/Users/Administrator/Desktop/mypic.png"))
self.picture.move(300, 300)
app = QtWidgets.QApplication(sys.argv)
run= program()
sys.exit(app.exec_())
在此代码中,当我单击 5 次按钮时,我的图片会出现,但图片变得非常小,如 pic1。 但是,当我将 setPixmap 和 picture.move 代码写入 init function 时,图片变为正常大小,如 pic2 所示。
解决您的问题的简单方法是在设置像素图后添加以下行:
self.picture.adjustSize()
直接原因是当显示小部件时,label 还没有像素图,所以它的几何图形已经设置为其最小尺寸(默认为 100x30)。 然后,当设置像素图时,label 不会自动更新其大小。
合乎逻辑的原因是你为你的小部件使用了固定的几何形状,这种方法通常不鼓励使用,原因有很多,最重要的是 window 中的元素应该始终调整它们的几何形状(大小和位置)以适应大小如果将 window 调整为更小的尺寸,可能会占用所有可用空间并防止元素变得不可见。
为避免这种情况,您应该始终使用布局管理器(在您的情况下,QVBoxLayout 就足够了)。
例如:
class program():
def __init__(self):
self.window = QtWidgets.QWidget()
# ...
layout = QtWidgets.QVBoxLayout(self.window)
layout.addWidget(self.text)
layout.addWidget(self.text2)
layout.addWidget(self.picture)
layout.addWidget(self.button)
# it's good practice to always show the window *after* adding all elements
self.window.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.