Search code examples
c++qtqwidget

Qt: Custom widget in QScrollArea


I am attempting to create a custom widget. My Widget renders itself unless it is inside a scroll area. The code below works. If I change the if(0) to an if(1) inside the MainWindow constructor, it will not render the "Hello World" string. I assume that I must (re)implement some additional methods, but so far I have not been able to find the correct ones with trial and error.

// 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();
}

Solution

  • You just have to give your HelloWidget a size and place.

    Add this line to your code.

    hello->setGeometry(QRect(110, 80, 120, 80)); 
    



    Or if you want to fill the scroll area with your widget:

    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 );
    }