我想让ui->centralWidget
具有QGridLayout
,可滚动。这样做最简单,最舒适的方法是什么?
我尝试过一个简约的项目,但它无法正常工作。 QScrollArea
出现在第二个窗口中,测试标签未显示在任何显示的窗口中。我究竟做错了什么?
mainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
gridLayout = new QGridLayout();
ui->centralWidget->setLayout(gridLayout);
scrollArea = new QScrollArea();
scrollArea->setBackgroundRole(QPalette::Dark);
scrollArea->setWidget(ui->centralWidget);
test = new QLabel("Test");
gridLayout->addWidget(test,0,0);
scrollArea->show();
}
MainWindow::~MainWindow()
{
delete ui;
}
mainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QGridLayout>
#include <QScrollArea>
#include <QLabel>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
QGridLayout *gridLayout;
QScrollArea *scrollArea;
QLabel *test;
};
#endif // MAINWINDOW_H
暗示@thuga之后的变化:
不显示标签。
mainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QWidget *testWidget = new QWidget(ui->centralWidget);
gridLayout = new QGridLayout(testWidget);
testWidget->setLayout(gridLayout);
scrollArea = new QScrollArea;
//scrollArea->setBackgroundRole(QPalette::Dark);
scrollArea->setWidget(testWidget);
scrollArea->setFrameShape(QFrame::NoFrame);
QHBoxLayout *mainLayout = new QHBoxLayout(ui->centralWidget);
ui->centralWidget->setLayout(mainLayout);
mainLayout->addWidget(scrollArea);
test = new QLabel("TESTTESTTESTTESTTEST");
testWidget->layout()->addWidget(test);
}
MainWindow::~MainWindow()
{
delete ui;
}
答案 0 :(得分:0)
@thuga帮助找到了解决方案,谢谢。我想分享一下。也许对某人有帮助。
以下是简约应用程序的代码:
<强> mainWindow.cpp 强>
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
mainWidget = new QWidget(ui->centralWidget);
gridLayout = new QGridLayout(mainWidget);
mainWidget->setLayout(gridLayout);
scrollArea = new QScrollArea;
scrollArea->setWidget(mainWidget);
scrollArea->setWidgetResizable(true);
mainLayout = new QHBoxLayout(ui->centralWidget);
ui->centralWidget->setLayout(mainLayout);
mainLayout->addWidget(scrollArea);
testLabel = new QLabel("TESTTESTTESTTEST");
gridLayout->addWidget(testLabel,0,0);
}
MainWindow::~MainWindow()
{
delete ui;
}
<强> mainWindow.h 强>
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QGridLayout>
#include <QScrollArea>
#include <QLabel>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
QWidget *mainWidget;
QHBoxLayout *mainLayout;
QGridLayout *gridLayout;
QScrollArea *scrollArea;
QLabel *testLabel;
};
#endif // MAINWINDOW_H