您的位置:首页 > 其它

Qwidget 添加 滚动条 QScrollArea

2014-01-23 14:23 495 查看
QScrollArea 可以方便的为Qwidget添加上滚动条;

一: 一般的方法:

来自帮助文档:

The QScrollArea class provides a scrolling view onto another widget.

A scroll area is used to display the contents of a child widget within a frame. If the widget exceeds the size of the frame, the view can provide scroll bars so that the entire area of the child widget can be viewed. The child widget must be specified with
setWidget(). For example:

QLabel *imageLabel = new QLabel;

QImage image("happyguy.png");

imageLabel->setPixmap(QPixmap::fromImage(image));

scrollArea = new QScrollArea;

scrollArea->setBackgroundRole(QPalette::Dark);

scrollArea->setWidget(imageLabel);

scrollArea->show(); // 注意添加这句话显示;

二:自定义QWidget子类:

有帮助文档:The QScrollArea class provides a scrolling view onto another widget ,这句话可以知道,QScrollArea 可以给任何QWidget添加滚动条;

但是一般自定义窗体添加滚动条不显示,如:

class CWidget : public QWidget

{

Q_OBJECT

public:

CWidget( QWidget * parent = 0 ): QWidget(parent)

{

}

virtual ~CWidget()

{

}

protected:

void paintEvent(QPaintEvent * pQPaintEvent )

{

QPainter painter( this );

painter.drawLine( 0,0, 100,100 );

}

};

void showCWidget() //这个函数没有显示滚动框中的CWidget ;

{

CWidget * pwidget = new CWidget;

scrollArea = new QScrollArea;

scrollArea->setBackgroundRole(QPalette::Dark);

scrollArea->setWidget(pwidget );

scrollArea->show();

}

查看帮助文档:

Size Hints and Layouts

When using a scroll area to display the contents of a custom widget, it is important to ensure that the size hint of the child widget is set to a suitable value. If a standard QWidget is used for the child widget,
it may be necessary to call QWidget::setMinimumSize() to ensure that the contents of the widget are shown correctly within the scroll area.

If a scroll area is used to display the contents of a widget that contains child widgets arranged in a layout, it is important to realize that the size policy of the layout will also determine the size of the widget. This is especially useful to know if you
intend to dynamically change the contents of the layout. In such cases, setting the layout's size constraint property to one which provides constraints on the minimum and/or maximum size of the layout (e.g., QLayout::SetMinAndMaxSize) will cause the size of
the scroll area to be updated whenever the contents of the layout changes.

For a complete example using the QScrollArea class, see the Image Viewer example. The example shows how to combine QLabel and QScrollArea to display an image.

所以上述函数可以修改为:

void showCWidget() //这个函数没有显示滚动框中的CWidget ;

{

CWidget * pwidget = new CWidget;

scrollArea = new QScrollArea;

scrollArea->setBackgroundRole(QPalette::Dark);

pwidget->setMinimumSize (100, 100 );

[b]pwidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); //可选;

[/b]scrollArea->setWidget(pwidget );

scrollArea->show();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: