PyQt:QScrollArea 内小部件的环绕式布局

Posted

技术标签:

【中文标题】PyQt:QScrollArea 内小部件的环绕式布局【英文标题】:PyQt: wrap-around layout of widgets inside a QScrollArea 【发布时间】:2017-05-28 01:01:53 【问题描述】:

我正在开发一个使用 PyQt4 记忆文本的应用程序。我想在气泡中显示所有单词,以便您查看单词的长度。但是当我的QScrollArea 中有所有气泡时,它们会一个接一个地对齐。我想让它们并排对齐,但使用自动换行。

我使用带有圆形边框的QLabel 让气泡起作用。但是现在我有了QLabel's 中的单词,PyQt 不会将它们视为单词 - 而是视为小部件。因此 PyQt 将一个小部件放在另一个小部件之下。我希望小部件并排对齐,直到它们到达行尾,然后它们应该环绕到下一行 - 这意味着 QLabel's 应该像文本文档中的单词一样。

到目前为止,这是我的代码:

f = open(r'myFile.txt')

class Bubble(QtGui.QLabel):
    def __init__(self, text):
        super(Bubble, self).__init__(text)
        self.word = text
        self.setContentsMargins(5, 5, 5, 5)

    def paintEvent(self, e):
        p = QtGui.QPainter(self)
        p.setRenderHint(QtGui.QPainter.Antialiasing,True)
        p.drawRoundedRect(0,0,self.width()-1,self.height()-1,5,5)
        super(Bubble, self).paintEvent(e)


class MainWindow(QtGui.QMainWindow):
    def __init__(self, text, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        self.setupUi(self)
        self.MainArea = QtGui.QScrollArea
        self.widget = QtGui.QWidget()
        vbox = QtGui.QVBoxLayout()
        self.words = []
        for t in re.findall(r'\b\w+\b', text):
            label = Bubble(t)
            label.setFont(QtGui.QFont('SblHebrew', 18))
            label.setFixedWidth(label.sizeHint().width())
            self.words.append(label)
            vbox.addWidget(label)
        self.widget.setLayout(vbox)
        self.MainArea.setWidget(self.widget)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    myWindow = MainWindow(f.read(), None)
    myWindow.show()
    sys.exit(app.exec_())

当我运行它时,我得到:

但我希望单词(包含单词的Qlabel's)彼此相邻,而不是彼此下方,就像这样(photoshopped):

我一直在进行大量研究,但没有任何答案可以帮助我将小部件彼此对齐。

【问题讨论】:

你为什么不用html 请解释您的问题 @ekhumoro,我正在编写一个计算机应用程序。网页不是html吗?另外,我还在学习html。 @eyllanesc,我已经在编辑中更好地解释了这个问题。 @CheynShmuel 您可以显示您想要的结果的图像。另外,PyQt 支持用于桌面应用程序的 HTML。 【参考方案1】:

这是一个 PyQt5 版本的 Flow Layout 演示脚本:

import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class FlowLayout(QtWidgets.QLayout):
    def __init__(self, parent=None, margin=-1, hspacing=-1, vspacing=-1):
        super(FlowLayout, self).__init__(parent)
        self._hspacing = hspacing
        self._vspacing = vspacing
        self._items = []
        self.setContentsMargins(margin, margin, margin, margin)

    def __del__(self):
        del self._items[:]

    def addItem(self, item):
        self._items.append(item)

    def horizontalSpacing(self):
        if self._hspacing >= 0:
            return self._hspacing
        else:
            return self.smartSpacing(
                QtWidgets.QStyle.PM_LayoutHorizontalSpacing)

    def verticalSpacing(self):
        if self._vspacing >= 0:
            return self._vspacing
        else:
            return self.smartSpacing(
                QtWidgets.QStyle.PM_LayoutVerticalSpacing)

    def count(self):
        return len(self._items)

    def itemAt(self, index):
        if 0 <= index < len(self._items):
            return self._items[index]

    def takeAt(self, index):
        if 0 <= index < len(self._items):
            return self._items.pop(index)

    def expandingDirections(self):
        return QtCore.Qt.Orientations(0)

    def hasHeightForWidth(self):
        return True

    def heightForWidth(self, width):
        return self.doLayout(QtCore.QRect(0, 0, width, 0), True)

    def setGeometry(self, rect):
        super(FlowLayout, self).setGeometry(rect)
        self.doLayout(rect, False)

    def sizeHint(self):
        return self.minimumSize()

    def minimumSize(self):
        size = QtCore.QSize()
        for item in self._items:
            size = size.expandedTo(item.minimumSize())
        left, top, right, bottom = self.getContentsMargins()
        size += QtCore.QSize(left + right, top + bottom)
        return size

    def doLayout(self, rect, testonly):
        left, top, right, bottom = self.getContentsMargins()
        effective = rect.adjusted(+left, +top, -right, -bottom)
        x = effective.x()
        y = effective.y()
        lineheight = 0
        for item in self._items:
            widget = item.widget()
            hspace = self.horizontalSpacing()
            if hspace == -1:
                hspace = widget.style().layoutSpacing(
                    QtWidgets.QSizePolicy.PushButton,
                    QtWidgets.QSizePolicy.PushButton, QtCore.Qt.Horizontal)
            vspace = self.verticalSpacing()
            if vspace == -1:
                vspace = widget.style().layoutSpacing(
                    QtWidgets.QSizePolicy.PushButton,
                    QtWidgets.QSizePolicy.PushButton, QtCore.Qt.Vertical)
            nextX = x + item.sizeHint().width() + hspace
            if nextX - hspace > effective.right() and lineheight > 0:
                x = effective.x()
                y = y + lineheight + vspace
                nextX = x + item.sizeHint().width() + hspace
                lineheight = 0
            if not testonly:
                item.setGeometry(
                    QtCore.QRect(QtCore.QPoint(x, y), item.sizeHint()))
            x = nextX
            lineheight = max(lineheight, item.sizeHint().height())
        return y + lineheight - rect.y() + bottom

    def smartSpacing(self, pm):
        parent = self.parent()
        if parent is None:
            return -1
        elif parent.isWidgetType():
            return parent.style().pixelMetric(pm, None, parent)
        else:
            return parent.spacing()

class Bubble(QtWidgets.QLabel):
    def __init__(self, text):
        super(Bubble, self).__init__(text)
        self.word = text
        self.setContentsMargins(5, 5, 5, 5)

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
        painter.drawRoundedRect(
            0, 0, self.width() - 1, self.height() - 1, 5, 5)
        super(Bubble, self).paintEvent(event)

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, text, parent=None):
        super(MainWindow, self).__init__(parent)
        self.mainArea = QtWidgets.QScrollArea(self)
        self.mainArea.setWidgetResizable(True)
        widget = QtWidgets.QWidget(self.mainArea)
        widget.setMinimumWidth(50)
        layout = FlowLayout(widget)
        self.words = []
        for word in text.split():
            label = Bubble(word)
            label.setFont(QtGui.QFont('SblHebrew', 18))
            label.setFixedWidth(label.sizeHint().width())
            self.words.append(label)
            layout.addWidget(label)
        self.mainArea.setWidget(widget)
        self.setCentralWidget(self.mainArea)

if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)
    window = MainWindow('Harry Potter is a series of fantasy literature')
    window.show()
    sys.exit(app.exec_())

【讨论】:

【参考方案2】:

我认为可以在 QTextBrowser 小部件中为此使用 html,但 Qt 的 rich-text engine 不支持气泡标签所需的 border-radius CSS 属性。

所以看起来您需要Flow Layout example 的 PyQt 端口。这可以“自动换行”容器内的一组小部件,还可以调整边距和水平/垂直间距。

这是一个演示脚本,它实现了FlowLayout 类并展示了如何在您的示例中使用它:

import sys
from PyQt4 import QtCore, QtGui

class FlowLayout(QtGui.QLayout):
    def __init__(self, parent=None, margin=-1, hspacing=-1, vspacing=-1):
        super(FlowLayout, self).__init__(parent)
        self._hspacing = hspacing
        self._vspacing = vspacing
        self._items = []
        self.setContentsMargins(margin, margin, margin, margin)

    def __del__(self):
        del self._items[:]

    def addItem(self, item):
        self._items.append(item)

    def horizontalSpacing(self):
        if self._hspacing >= 0:
            return self._hspacing
        else:
            return self.smartSpacing(
                QtGui.QStyle.PM_LayoutHorizontalSpacing)

    def verticalSpacing(self):
        if self._vspacing >= 0:
            return self._vspacing
        else:
            return self.smartSpacing(
                QtGui.QStyle.PM_LayoutVerticalSpacing)

    def count(self):
        return len(self._items)

    def itemAt(self, index):
        if 0 <= index < len(self._items):
            return self._items[index]

    def takeAt(self, index):
        if 0 <= index < len(self._items):
            return self._items.pop(index)

    def expandingDirections(self):
        return QtCore.Qt.Orientations(0)

    def hasHeightForWidth(self):
        return True

    def heightForWidth(self, width):
        return self.doLayout(QtCore.QRect(0, 0, width, 0), True)

    def setGeometry(self, rect):
        super(FlowLayout, self).setGeometry(rect)
        self.doLayout(rect, False)

    def sizeHint(self):
        return self.minimumSize()

    def minimumSize(self):
        size = QtCore.QSize()
        for item in self._items:
            size = size.expandedTo(item.minimumSize())
        left, top, right, bottom = self.getContentsMargins()
        size += QtCore.QSize(left + right, top + bottom)
        return size

    def doLayout(self, rect, testonly):
        left, top, right, bottom = self.getContentsMargins()
        effective = rect.adjusted(+left, +top, -right, -bottom)
        x = effective.x()
        y = effective.y()
        lineheight = 0
        for item in self._items:
            widget = item.widget()
            hspace = self.horizontalSpacing()
            if hspace == -1:
                hspace = widget.style().layoutSpacing(
                    QtGui.QSizePolicy.PushButton,
                    QtGui.QSizePolicy.PushButton, QtCore.Qt.Horizontal)
            vspace = self.verticalSpacing()
            if vspace == -1:
                vspace = widget.style().layoutSpacing(
                    QtGui.QSizePolicy.PushButton,
                    QtGui.QSizePolicy.PushButton, QtCore.Qt.Vertical)
            nextX = x + item.sizeHint().width() + hspace
            if nextX - hspace > effective.right() and lineheight > 0:
                x = effective.x()
                y = y + lineheight + vspace
                nextX = x + item.sizeHint().width() + hspace
                lineheight = 0
            if not testonly:
                item.setGeometry(
                    QtCore.QRect(QtCore.QPoint(x, y), item.sizeHint()))
            x = nextX
            lineheight = max(lineheight, item.sizeHint().height())
        return y + lineheight - rect.y() + bottom

    def smartSpacing(self, pm):
        parent = self.parent()
        if parent is None:
            return -1
        elif parent.isWidgetType():
            return parent.style().pixelMetric(pm, None, parent)
        else:
            return parent.spacing()

class Bubble(QtGui.QLabel):
    def __init__(self, text):
        super(Bubble, self).__init__(text)
        self.word = text
        self.setContentsMargins(5, 5, 5, 5)

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
        painter.drawRoundedRect(
            0, 0, self.width() - 1, self.height() - 1, 5, 5)
        super(Bubble, self).paintEvent(event)

class MainWindow(QtGui.QMainWindow):
    def __init__(self, text, parent=None):
        super(MainWindow, self).__init__(parent)
        self.mainArea = QtGui.QScrollArea(self)
        self.mainArea.setWidgetResizable(True)
        widget = QtGui.QWidget(self.mainArea)
        widget.setMinimumWidth(50)
        layout = FlowLayout(widget)
        self.words = []
        for word in text.split():
            label = Bubble(word)
            label.setFont(QtGui.QFont('SblHebrew', 18))
            label.setFixedWidth(label.sizeHint().width())
            self.words.append(label)
            layout.addWidget(label)
        self.mainArea.setWidget(widget)
        self.setCentralWidget(self.mainArea)

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = MainWindow('Harry Potter is a series of fantasy literature')
    window.show()
    sys.exit(app.exec_())

【讨论】:

非常感谢!这正是我想要的!虽然我很伤心地说我不明白为什么。两个问题:(1)有没有办法从右到左显示小部件? (2) 有没有办法将小部件与任何方向对齐,或者证明它们的合理性? @CheynShmuel。也许——但这需要很多额外的工作。这就是我之前建议使用 html 的原因——它解决了布局文档的所有困难,并且可以轻松地以各种不同的方式格式化单词。不幸的是,QTextEditQTextBrowser 类不支持现代 html/css 的完整功能集,因此您无法获得像圆角这样的花哨的东西。但支持从右到左和对齐方式 我知道这可能很难,但至少是可能的。你至少能给我指出正确的方向吗?我知道这可能很难,所以您至少可以提供一点帮助吗? @CheynShmuel。我移植到 PyQt 的原始 FlowLayout 类是由 Qt 开发人员编写的,他们知道如何编写自定义布局。我自己没有这方面的经验。 Qt 文档有这个:How to Write A Custom Layout Manager。但实际上,这对于一个 SO 问题来说工作量太大了。我的建议是让你的程序使用 html (这将是快速和容易的),然后再担心像圆角这样的花哨的东西。如果您进行一些网络搜索,您甚至可能会找到相应的工作轮次。 谢谢。我会努力做到的

以上是关于PyQt:QScrollArea 内小部件的环绕式布局的主要内容,如果未能解决你的问题,请参考以下文章

PyQt5:QScrollArea 保持 Pixmap 纵横比

将小部件放在 QScrollArea 的中心

Python + PyQt5:如何将QScrollArea用于一个或多个QGroupBox?

Qt - QScrollArea 小部件剪辑内容

无法动态地将小部件添加到 QScrollArea 对象

Qt:QScrollArea 中的自定义小部件