簡體   English   中英

制作小部件的可滾動區域

[英]Make an scrollable area of widgets

對於作業,我需要使用C ++和Qt創建類似於WordPress的CMS。 在主頁上,所有帖子必須顯示在帶有滾動條的區域中。 我嘗試使用QScrollArea,但問題似乎出在布局上。 它將內部的對象縮小到適合提供的高度。 我試圖通過將對象的大小策略設置為fixed來解決此問題,但令人驚訝的是,這根本沒有任何區別!

這是我要制作的窗口代碼:

#include "cms.h"
#include "user.h"
#include "post.h"
#include "uipost.h"
#include <QStyle>
#include <QDesktopWidget>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QScrollArea>
#include <QPushButton>
#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include <QLabel>
#include <QSizePolicy>

CMS::CMS(User & SignedInUser, QWidget *parent) : QWidget(parent), signedInUser(SignedInUser) {
    User admin;
    Post temp(admin);

    QHBoxLayout *mainLayout = new QHBoxLayout();

    QScrollArea *posts = new QScrollArea();
    posts->setWidgetResizable(true);
    posts->setFrameShape(QFrame::NoFrame);
    QVBoxLayout *postsLayout = new QVBoxLayout(posts);
    for (int i = 0; i < 50; i++) {
    QLabel *label = new QLabel(tr("some sample label"));
    postsLayout->addWidget(label);
    /* Here the posts will be read from file and shown. Since the class for posts isn't still ready, I'm just trying to try it with label and later on use that class.
     * That class inheritances QFrame.
     */
    }

    QVBoxLayout *buttonsLayout = new QVBoxLayout();
    buttonsLayout->setAlignment(Qt::AlignTop);
    QPushButton *manUsers = new QPushButton(tr("Manage Users"));
    buttonsLayout->addWidget(manUsers);
    QPushButton *addUser = new QPushButton(tr("Add a User"));
    buttonsLayout->addWidget(addUser);
    QPushButton *logout = new QPushButton(tr("Log Out"));
    buttonsLayout->addWidget(logout);
    QPushButton *exit = new QPushButton(tr("Exit"));
    buttonsLayout->addWidget(exit);

    mainLayout->addWidget(posts);
    mainLayout->addLayout(buttonsLayout);
    setLayout(mainLayout);

    setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, size(), QDesktopWidget().availableGeometry())); // Centerizing the window
    setFixedSize(size()); // Making the window unresizable

    connect(exit, &QPushButton::clicked, this, &QWidget::close);
}

類定義不包含任何特定內容,只是為了確保不遺漏任何內容:

#ifndef CMS_H
#define CMS_H

#include <QMainWindow>
#include "user.h"

namespace Ui {
    class CMS;
}

class CMS : public QWidget {
    Q_OBJECT
private:
    User & signedInUser;
public:
    CMS(User & SignedInUser, QWidget *parent = nullptr);
};

#endif // CMS_H

我在您的代碼中添加了一行(取消注釋並重新排序某些行后,請下次提供MCVE ),這是

postsLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);

給你的構造函數。

具有QLabels的QScrollArea

注意底部的切口。

作為參考,我建議相當好的文檔 對於進一步的主題QScrollArea (到底在哪是QScrollBars ?)我建議你通過工作, 這個例子


還要注意,有人可能會說您的方法不適合您的任務。

我找到了解決方案。 顯然,我需要定義一個小部件,將滾動區域設置為該小部件,然后將包含元素的布局設置為該小部件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM