首页 > 解决方案 > Qt:了解 QScrollArea::widgetResizable 属性

问题描述

我正在试验 Qt 5 QScrollArea(在 Python 和 PyQt 中,但我相信这个问题同样适用于 C++ Qt)。

Qt 文档QScrollArea::widgetResizable说“如果此属性设置为 false(默认值),则滚动区域将遵循其小部件的大小。” 通过“它的小部件”,我假设它意味着在滚动区域中查看的小部件。

但是,在下面的程序中,我在滚动区域内显示了一个图像标签,但滚动区域似乎没有“尊重其小部件的大小”,因为该图像从一开始就部分隐藏。

文档还说“不管这个属性如何,您都可以使用 以编程方式调整小部件widget()->resize()的大小,滚动区域将自动调整为新的大小。” 但是,我确实为查看的小部件调用了调整大小,但没有任何反应。

文档还说“如果此属性设置为 true,则滚动区域将自动调整小部件的大小,以避免滚动条可以避免,或者利用额外的空间。” 但是,我看不到任何调整大小,即使调整了小部件的大小,也可以避免滚动条。

这是我是否将属性设置为TrueorFalse以及是否调用所看到的widget().resize()

在此处输入图像描述

显然,我必须在这里遗漏一些非常基本的东西。它是什么?

编辑:这个问题的主要目的是了解它的widgetResizable工作原理和作用。将图像放入窗口是次要目标。

from PyQt5.QtCore import QSize
from PyQt5.QtGui import QImage, QPalette, QPixmap
from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel, QScrollArea


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        image = QImage("happyguy.png")
        imageLabel = QLabel()
        imageLabel.setPixmap(QPixmap.fromImage(image))

        scrollArea = QScrollArea()
        scrollArea.setBackgroundRole(QPalette.Dark)
        scrollArea.setWidget(imageLabel)

        scrollArea.setWidgetResizable(True)

        scrollArea.widget().resize(QSize(10, 10))

        self.setCentralWidget(scrollArea)


app = QApplication([])
w = MainWindow()
w.show()
app.exec_()

这是happyguy.pgn文件:

快乐的家伙.pgn

标签: qtqscrollarea

解决方案


scrollArea.setWidgetResizable(True)将 imageLabel 的大小调整控制权交给 scrollArea。所以下一行将scrollArea.widget().resize(QSize(10, 10))被系统覆盖。

一种适用于 Windows 的解决方案(调整主窗口大小以适合图像大小)。

from PyQt5.QtGui import QImage, QPalette, QPixmap
from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel, QScrollArea, QFrame


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        image = QImage("happyguy.png")
        imageLabel = QLabel()
        imageLabel.setPixmap(QPixmap.fromImage(image))

        scrollArea = QScrollArea()
        scrollArea.setFrameShape(QFrame.NoFrame)
        scrollArea.setBackgroundRole(QPalette.Dark)
        scrollArea.setWidget(imageLabel)

        self.setCentralWidget(scrollArea)
        self.resize(image.size())


app = QApplication([])
w = MainWindow()
w.show()
app.exec_()

使用QScrollArea.setMinimumSize

from PyQt5.QtGui import QImage, QPalette, QPixmap
from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel, QScrollArea, QFrame


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        image = QImage("happyguy.png")
        imageLabel = QLabel()
        imageLabel.setPixmap(QPixmap.fromImage(image))

        scrollArea = QScrollArea()
        scrollArea.setFrameShape(QFrame.NoFrame)
        scrollArea.setBackgroundRole(QPalette.Dark)
        scrollArea.setWidget(imageLabel)
        scrollArea.setMinimumSize(image.size())

        self.setCentralWidget(scrollArea)


app = QApplication([])
w = MainWindow()
w.show()
app.exec_()

推荐阅读