在 window 的顶部中央显示 QLabel

Display a QLabel at the top-centre of the window

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

我尝试了很多方法,但都没有成功。

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_()





您应该使用带有布局的中央小部件来控制子小部件在主 window 中的大小和位置。这是您的 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, 0, 0, Qt.AlignTop | Qt.AlignHCenter)

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

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

        self.setCentralWidget(widget)

请注意,无需继续调用 show(),因为这一切都由布局自动处理。有关详细信息,请参阅 Qt 文档中的 Layout Management 文章。