[英]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.