Qt:QScrollArea中的自定义小部件

use*_*974 5 c++ qt qwidget

我正在尝试创建自定义小部件.我的Widget渲染自己,除非它在滚动区域内.以下代码有效.如果我在MainWindow构造函数中将if(0)更改为if(1),它将不会呈现"Hello World"字符串.我假设我必须(重新)实现一些额外的方法,但到目前为止,我无法通过反复试验找到正确的方法.

// hellowidget.h
#ifndef HELLOWIDGET_H
#define HELLOWIDGET_H

#include <QtGui>

class HelloWidget : public QWidget
{
    Q_OBJECT
public:
    HelloWidget(QWidget *parent = 0);
    void paintEvent(QPaintEvent *event);
};

#endif // HELLOWIDGET_H

// hellowidget.cpp
#include "hellowidget.h"
HelloWidget::HelloWidget(QWidget *parent)
: QWidget(parent)
{
}
void HelloWidget::paintEvent(QPaintEvent *event)
{
     QPainter painter(this);
     painter.drawText(rect(), Qt::AlignCenter, "Hello World");
}

// mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QtGui>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
};

#endif // MAINWINDOW_H

// mainwindow.cpp
#include "mainwindow.h"
#include "hellowidget.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    HelloWidget *hello = new HelloWidget;
    QWidget *central = hello;

    if( 0 )
    {
        QScrollArea *scroll = new QScrollArea ;
        scroll->setWidget(hello);
        central = scroll;
    }

   setCentralWidget( central );
}

MainWindow::~MainWindow()
{
}

// main.cpp
#include <QtGui/QApplication>
#include "mainwindow.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*imW 8

你只需要给你的HelloWidget一个大小和位置.

将此行添加到您的代码中.

hello->setGeometry(QRect(110, 80, 120, 80)); 
Run Code Online (Sandbox Code Playgroud)



或者,如果要使用小部件填充滚动区域:

MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
    QScrollArea *const scroll(new QScrollArea);
    QHBoxLayout *const layout(new QHBoxLayout(scroll)); 
    HelloWidget *const hello(new HelloWidget);
    hello->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
    layout->addWidget(hello);
    setCentralWidget( scroll );
}
Run Code Online (Sandbox Code Playgroud)