[英]PyQt5 QWidget.setGeometry() not working for QLabel
我正在PyQt5中开发一个非常简单的应用程序来显示和排序图像。 我是Python和Qt的新手,我遇到了一些问题。 我正在尝试在QLabel对象中显示QPixmap图像,并且它们正确显示。 但是,它们在默认情况下排成一行,我无法弄清楚如何移动它们。
(我知道代码很糟糕,但是我想在它干净之前让它工作。)
这是我的代码:
class ImageClassifier(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
hbox = QtWidgets.QHBoxLayout(self)
mainImg = QPixmap("img.png")
xmplImg0 = QPixmap("img0.png")
xmplImg1 = QPixmap("img1.png")
xmplImg2 = QPixmap("img2.png")
xmplImg3 = QPixmap("img3.png")
lbl = QtWidgets.QLabel(self)
lbl0 = QtWidgets.QLabel(self)
lbl1 = QtWidgets.QLabel(self)
lbl2 = QtWidgets.QLabel(self)
lbl3 = QtWidgets.QLabel(self)
lbl.setPixmap(mainImg)
lbl0.setPixmap(xmplImg0)
lbl1.setPixmap(xmplImg1)
lbl2.setPixmap(xmplImg2)
lbl3.setPixmap(xmplImg3)
hbox.addWidget(lbl)
hbox.addWidget(lbl0)
hbox.addWidget(lbl1)
hbox.addWidget(lbl2)
hbox.addWidget(lbl3)
lbl0.setGeometry(30, 30, 30, 30)
self.setLayout(hbox)
self.move(300, 200)
self.setWindowTitle('Fruit Classifier')
self.show()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ic = ImageClassifier()
sys.exit(app.exec_())
lbl0.setGeometry()
函数根本没有做任何事情,我也不知道为什么。 有没有人知道解决这个问题的方法,或者更好的方法来设置QLabel对象的位置?
请遵循以下项目符号。
[更新]看看我想说的话。 更好的例子:
如果使用BoxLayout,对象的位置将无法满足您的要求。 它将遵循BoxLayout政策。 您还传递了(自我)QLabel使QWidget成为其父级的原因。 那是一团糟。
请查看以下代码。 我没有BoxLayout,我只是说我是谁(Qlabel)的父母。 所以我会表现得像我的“爸爸”说的那样。 所以现在你可以移动它。
import sys
from PyQt5 import QtWidgets
class ImageClassifier(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
self.setFixedSize(500,500)
lbl = QtWidgets.QLabel(self)
lbl.setFixedSize(50,50)
lbl0 = QtWidgets.QLabel(self)
lbl0.setFixedSize(50, 50)
lbl1 = QtWidgets.QLabel(self)
lbl1.setFixedSize(50, 50)
lbl2 = QtWidgets.QLabel(self)
lbl2.setFixedSize(50, 50)
lbl3 = QtWidgets.QLabel(self)
lbl3.setFixedSize(50, 50)
lbl.setStyleSheet("""background-color: red;""")
lbl0.setStyleSheet("""background-color: green;""")
lbl1.setStyleSheet("""background-color: blue;""")
lbl2.setStyleSheet("""background-color: yellow;""")
lbl3.setStyleSheet("""background-color: black;""")
lbl0.move(50,50)
lbl1.move(100, 100)
lbl2.move(150, 150)
lbl3.move(150, 150)
self.move(300, 200)
self.setWindowTitle('Fruit Classifier')
self.show()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
ic = ImageClassifier()
sys.exit(app.exec_())
这只是一种简单的方法。 您最好创建自己的继承QLabel的Label。 并根据自己的意愿个性化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.