首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PQYT使QGridLayout可滚动

PQYT使QGridLayout可滚动
EN

Stack Overflow用户
提问于 2022-06-08 00:05:12
回答 1查看 31关注 0票数 0

我想知道是否可以将QScrollArea添加到QGridLayout中?下面是我的尝试,然而,它总是失败的错误。

代码语言:javascript
复制
TypeError: setWidget(self, QWidget): argument 1 has unexpected type 'QGridLayout'

此方法仅可用于组合框和列表框吗?我基本上是将QPixmap图像传递到需要滚动的QGridLayout中。任何帮助都非常感谢,谢谢。

代码语言:javascript
复制
import sys

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class PicClip(QWidget):

    def __init__(self):
        super().__init__()
        # Load image
        self.im = QPixmap("1.jpg")
        self.im1 = QPixmap("1.jpg")
        # Label 1
        self.label = QLabel()
        self.label.setPixmap(self.im)
        # Label 2
        self.label1 = QLabel()
        self.label1.setPixmap(self.im1)
        # Make Grid
        self.grid = QGridLayout()
        # Create widgets to grid
        self.grid.addWidget(self.label, 0, 1, alignment=Qt.AlignCenter)
        self.grid.addWidget(self.label1, 1, 1, alignment=Qt.AlignCenter)
        # Set layout of Grid
        self.setLayout(self.grid)
        # Scroll 
        scroll = QScrollArea()
        scroll.setWidget(self.grid)
        scroll.setWidgetResizable(True)
        # Show 
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = PicClip()
    sys.exit(app.exec_())
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-06-08 00:17:17

self.grid是布局,您正在尝试使用setWidget函数添加布局。setWidget函数只获取QWidget

简单的技巧是添加包装器QWidget并设置self.grid作为其布局。

代码语言:javascript
复制
import sys

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class PicClip(QMainWindow): # I modified this line to show window properly

    def __init__(self):
        super().__init__()
        # Load image
        self.im = QPixmap("1.jpg")
        self.im1 = QPixmap("1.jpg")
        # Label 1
        self.label = QLabel()
        self.label.setPixmap(self.im)
        # Label 2
        self.label1 = QLabel()
        self.label1.setPixmap(self.im1)
        # Make Grid
        self.grid = QGridLayout()
        # Create widgets to grid
        self.grid.addWidget(self.label, 0, 1, alignment=Qt.AlignCenter)
        self.grid.addWidget(self.label1, 1, 1, alignment=Qt.AlignCenter)
        # Set layout of Grid
        self.setLayout(self.grid)
        # Scroll
        scroll = QScrollArea()
        # add wrapper widget and set its layout
        wrapper_widget = QWidget()
        wrapper_widget.setLayout(self.grid)
        scroll.setWidget(wrapper_widget)
        scroll.setWidgetResizable(True)
        # Show
        self.setCentralWidget(scroll)  # I modified this line to show window properly
        self.show()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = PicClip()
    sys.exit(app.exec_())
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72538711

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档