为什么标签显示不全?

Why does the label not fully display?

我正在学习如何使用 PyQt5,我遇到了 "my first label" 没有在我的屏幕上完成显示的问题。

在运行代码后显示:

代码:

from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtCore import *
from PyQt5.QtGui  import *
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys

QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True) #enable highdpi scaling
QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True) #use highdpi icons

def window():
  app = QApplication(sys.argv)
  win = QMainWindow()
  win = QMainWindow()
  win.setGeometry(200, 200, 400, 400)
  win.setWindowTitle("Tech with Aeijan")
  label = QtWidgets.QLabel(win)
  label.setText("my first label!")
  label.move(50,50)

  win.show()
  sys.exit(app.exec_())

window()

QLabel 根据(可能的)父布局管理器调整其内容,但您没有使用任何布局管理器,因此它不知道如何正确显示自身或调整其大小来执行此操作。

最简单的解决方案是调用 label.adjustSize(),这将导致标签自行调整大小,以便能够显示其内容。

虽然这不是一个好主意:您正在尝试为小部件使用固定位置(出于多种原因,这通常被认为是一件坏事);结果将是,如果标签文本太大并且用户调整 window 的大小,文本将不会像它应该的那样完全可见,标签也不知道如何调整大小或最终将其内容包装到请确保显示所有文本。

更好的方法是使用layout manager, but that is a solution reserved for simpler widgets (like a QWidget or a QDialog); a QMainWindow doesn't work like that, and it requires a central widget to be set来确保其内容被正确显示和管理。

在您的情况下,您可以简单地使用 self.setCentralWidget(label),但这会阻止您向 window 添加任何其他小部件。

应该使用 "container" 小部件,并且该小部件将被设置为主 window 的中心部件;然后您可以为该小部件设置布局并为其添加标签:

def window():
    app = QApplication(sys.argv)
    win = QMainWindow()

    central = QWidget()
    win.setCentralWidget(central)

    layout = QVBoxLayout()
    central.setLayout(layout)
    # alternatively, the above is the same as this:
    # layout = QVBoxLayout(central)

    label = QtWidgets.QLabel(win)
    label.setText("my first label!")
    layout.addWidget(label)

    # ...