2017-05-15 52 views
0

對於任務,我需要使用C++和Qt創建一個類似於WordPress的CMS。在主頁面中,所有帖子必須顯示在帶滾動條的區域中。我試過使用QScrollArea,但問題似乎是佈局。它縮小內部物體以適應所提供的高度。我試圖通過設置對象的大小策略來解決這個問題,但令人驚訝的是,這根本沒有任何區別!製作可滾動區域的小部件

這裏的代碼我試圖使窗口:

#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 

回答

0

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

1

我加(註釋和重新排序某行後,請在下一次提供MCVE),這是

postsLayout->setSizeConstraint(QLayout::SetMinAndMaxSize); 

給你的構造函數。

QScrollArea with QLabels

注意切口底部。

僅供參考我建議不錯documentation。對於QScrollArea(地獄是QScrollBars?)的其他主題,我建議你通過this example工作。


另請注意,有人可能會認爲您的方法不適合您的任務。

+0

非常感謝您的參考和鏈接。 –