使用QScrollArea可以帮助我们实现让一个widget的内容带有滚动条,用户可以通过拖动滚动条来查看更多内容,
代码示例如下:
1.带有滚动条的widget列表
- #include "widget.h"
- Widget::Widget(QWidget *parent)
- : QWidget(parent)
- {
- list=new QListWidget();
- lay=new QHBoxLayout();
- QSizeGrip *gr=new QSizeGrip(list);//用来重设widget的size
- scroll=new QScrollArea();
- scroll->setWidget(list);
- scroll->setAlignment(Qt::AlignLeft);
- // scroll->setWidgetResizable(true);
- scroll->setBackgroundRole(QPalette::Dark);// 设置滚动区域的背景
- //win=new QWidget();
- item1=new QListWidgetItem("BlueHills",list);//向widget列表中加入一项
- item2=new QListWidgetItem("Sunset",list);
- item3=new QListWidgetItem("Water lilies",list);
- item4=new QListWidgetItem("Himaliya is a good place",list);
- item5=new QListWidgetItem("Ooty",list);
- item6=new QListWidgetItem("Hero Honda",list);
- item7=new QListWidgetItem("",list);
- item8=new QListWidgetItem("orkut.com",list);
- item9=new QListWidgetItem("sunrise",list);
- item10=new QListWidgetItem("OVI",list);
- item11=new QListWidgetItem("Nokia N97",list);
- item12=new QListWidgetItem("forum.nokia.com",list);
- item13=new QListWidgetItem("wellcome to Qt",list);
- item14=new QListWidgetItem("Qt rocks for s60",list);
- item15=new QListWidgetItem("Symbian c++",list);
- item16=new QListWidgetItem("5800 Xpress Music",list);
- item17=new QListWidgetItem("My best Phone",list);
- item18=new QListWidgetItem("I like N97",list);
- item19=new QListWidgetItem("Go for 5800",list);
- item20=new QListWidgetItem("America",list);
- // lay->addWidget(list);
- lay->addWidget(scroll);
- setLayout(lay);//setting layout
- showMaximized();
- }
- Widget::~Widget()
- {
- }
复制代码
截图如下:
2.带有滚动条的图片显示
- Widget::Widget(QWidget *parent)
- : QWidget(parent)
- {
- QLabel *imageLabel = new QLabel(this);
- QImage image("E:\\flower.png",this);
- lay=new QHBoxLayout(this);
- imageLabel->setPixmap(QPixmap::fromImage(image));
- scrollArea = new QScrollArea(this);
- scrollArea->setWidgetResizable(1);
- scrollArea->setBackgroundRole(QPalette::Dark);
- scrollArea->setWidget(imageLabel);
- lay->addWidget(scrollArea);
- setLayout(lay);
- }
- Widget::~Widget()
- {
- }
复制代码
截图如下: