在窗口的顶部中心显示QLabel

我无法自行设置PyQt。我的想法是创建一个具有歌曲标题和专辑封面的音乐播放器。我已经成功创建了自己的窗口并添加了专辑封面。但是我无法在正确的位置添加标签。我希望歌曲标题位于窗口的顶部中心,如下图所示:

在窗口的顶部中心显示QLabel

我尝试了很多方法,但是没有运气。

import sys
from PyQt5.QtGui import QIcon,QPixmap,QFontDatabase,QFont
from PyQt5.QtWidgets import QApplication,QLabel,QMainWindow,QWidget,QGridLayout,QDialog
from PyQt5.QtCore import Qt,QRect

# Subclass QMainWindow to customise your application's main window
class MainWindow(QMainWindow):
    def __init__(self,*args,**kwargs):
        super(MainWindow,self).__init__(*args,**kwargs)
        self.title = 'PyQt5 simple window - pythonspot.com'
        self.left = 10
        self.top = 10
        self.width = 480
        self.height = 320
        self.initUI()

        self.setWindowTitle("My Awesome App")

    def add_font(self):
        # Load the font:
        font_db = QFontDatabase()
        font_id = font_db.addApplicationFont('American Captain.ttf')
        families = font_db.applicationFontFamilies(font_id)
        ttf_font = QFont(' '.join(families),15)
        return ttf_font

    def initUI(self):
        ttf_font = self.add_font()
        w = QWidget()
        self.setWindowTitle(self.title)
        self.setGeometry(self.left,self.top,self.width,self.height)
        self.show()
        album_cover = QLabel(self)
        album_pic = QPixmap('resized_image.jpg')
        album_cover.setPixmap(album_pic)

        album_cover.setalignment(Qt.AlignCenter)
        self.setCentralWidget(album_cover)


        art_alb = QLabel(self)
        art_alb.setfont(ttf_font)
        art_alb.setText("michael buble - christmas")
        art_alb.setGeometry(self.x,self.y,self.x,self.y)
        art_alb.setalignment(Qt.AlignTop | Qt.AlignCenter )
        art_alb.show()
        self.show()



app = QApplication(sys.argv)

window = MainWindow()
window.show()

app.exec_()





c5577855 回答:在窗口的顶部中心显示QLabel

您应该使用具有布局的中央窗口小部件来控制子窗口小部件的大小和在主窗口中的位置。这是您应该initUI的方法的重写,该方法应该可以执行您想要的操作:

class MainWindow(QMainWindow):
    ...

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left,self.top,self.width,self.height)

        widget = QWidget()
        layout = QGridLayout(widget)

        art_alb = QLabel(self)
        ttf_font = self.add_font()
        art_alb.setFont(ttf_font)
        art_alb.setText("michael buble - christmas")

        layout.addWidget(art_alb,Qt.AlignTop | Qt.AlignHCenter)

        album_cover = QLabel(self)
        album_pic = QPixmap('image.jpg')
        album_cover.setPixmap(album_pic)

        layout.addWidget(album_cover,1,Qt.AlignHCenter)
        layout.setRowStretch(1,1)

        self.setCentralWidget(widget)

请注意,由于布局会自动处理所有操作,因此无需继续调用show()。有关更多信息,请参见Qt文档中的Layout Management文章。

本文链接:https://www.f2er.com/3089419.html

大家都在问