Monday, July 5, 2010

Scrolling in custom widget using QScrollArea in Qt

I remembered when I was creating custom view in S60 and I required to implement scrolling. I needed to create my own logic for scrolling using windowing and drawing component manually when comes in to visible area.

Now I am doing similar thing using Qt and and can't believe that solution can be so simple. Qt has class named QScrollArea which main purpose it to support scrolling for such custom view.

Following is code from my application. In this code I want to make certain part of my view to be scrollable and certain part to be remain static.

The part where I want scrolling, for that part I am creating widget with layout and adding all its child widget in layout and then adding that widget to QScrollArea.

QWidget* SampleUI::createMessageWidget()
{
    QLable  label= new QLabel("");
    label->setAlignment(Qt::AlignLeft);
    label->setWordWrap( true );

    ignoreBtn = new QPushButton("Ignore Message");
    ignoreBtn->setEnabled( false );
    QObject::connect(ignoreBtn,SIGNAL(clicked()),SLOT(ignoreMessage()));

    QWidget* messageWidget = new QWidget;
    QVBoxLayout* mainLayout = new QVBoxLayout( messageWidget);
    mainLayout->addWidget( label );
    mainLayout->addWidget( ignoreBtn);

    QScrollArea* scrollArea = new QScrollArea(this);
    scrollArea->setWidgetResizable(true);
    scrollArea->setWidget(messageWidget);
    return scrollArea;
}


Now I am adding this scrollable widget and static widget in custom view's layout.

void SampleUI::SampleUI(QWidget *parent) :QWidget(parent)
{
    QWidget* messageWidget = createMessageWidget();
    QLabel status = new QLabel("");
    status->setAlignment(Qt::AlignRight);

    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(messageWidget);
    mainLayout->addWidget( mStatus );
}

No comments:

Post a Comment