标题:【提问】关于QPainter的使用,stretch的含义
作者:mudfish
日期:2005-11-14 13:44
内容:
各位好,我在学习使用QPainter类,遇到问题如下:
目的: 想在弹出的对话框DlgImageView中显示一块背景为黑色,绘有一些绿色连线的图.
代码:
DlgImageView::DlgImageView( QWidget* parent,const char* name, bool modal, WFlags fl ) : QDialog( parent, name, modal, fl )
{
...
QVBoxLayout *vb = new QVBoxLayout( this, 3 );
vb->addWidget( new QLabel( "Draw Image Test:", this ) );
//add Read Image View
QWidget *imageRead = new QWidget(this);
imageRead->setMinimumHeight( 30 );
imageRead->setBackgroundColor( black );
setMinimumWidth( points );
QPainter p(imageRead);
//draw some lines to test
p.setPen( red );
p.drawLine( 0, 25, 10, 25 );
p.drawText( 0, 25, "10" );
p.drawText( 0, 23, "0" );
p.setPen( green );
for ( int i = 0; i < points-1; i++ )
{
int y1 = i*5;
int y2 = (i+1)*5;
p.drawLine(i, y1, (i+1), y2);
}
vb->addWidget( imageRead, 100 );
vb->addWidget( new QLabel( "The end", this ) );
}
结果: 黑色背景可以显示,但上面没有线条可以显示.见附图.
问题: 1. 我的代码错在哪里?
2. 语句 vb->addWidget( imageRead, 100 ) 中的参数"100"代表stretch.
关于stretch的解释是
"Widgets are normally created without any stretch factor set. When they are laid out in a layout the widgets are given a share of space in accordance with their QWidget::sizePolicy() or their minimum size hint whichever is the greater. Stretch factors are used to change how much space widgets are given in proportio ..
#1 [mudfish 11-14 15:56]
改成在paintEvent()中绘制线条,问题差不多可以定位在
QPainter p(...);
这句话上.
修改后的代码如下:
FormImageView::FormImageView( QWidget* parent,const char* name, bool modal, WFlags fl ) : QDialog( parent, name, modal, fl )
{
setName( "FormImageView" );
resize( 240, 320 );
setCaption( tr( "read/write speed compare" ) );
QVBoxLayout *vb = new QVBoxLayout( this, 6 );
//vb->addWidget( new QLabel( "read/write speed compare:", this ) );
vb->addWidget( new QLabel( "read speed compare Image:", this ) );
//add Read Image View
imageRead = new QWidget(this);
imageRead->setMinimumHeight( 30 );
setMinimumWidth(10 );
imageRead->setBackgroundColor( black );
vb->addWidget( imageRead, 100 );
vb->addWidget( new QLabel( "write speed compare Image:", this ) );
update();
}
void FormImageView::paintEvent(QPaintEvent *)
{
int points = 10;
int *userLoad = NULL;
userLoad = new int ;
for ( int i = 0; i < points; i++ )
{
userLoad = i;
}
QPainter p(this); //QPainter p(imageRead);
//draw some lines to test
p.setPen( red );
p.drawLine( 0, 0, 800, 805 );
p.drawText( 0, 25, "10" );
p.drawText( 0, 23, "0" );
p.setPen( green );
for ( i ..
#2 [tdns 11-16 15:12]
问题很明显啊,你的错误在于你重载的是FormImageView的paintEvent,在这个函数里面你重画的是你的Dialog。如果想在imageRead里面画图,那么就要重载imageRead的paintEvent函数
我想办法应该是,把imageRead定义成一个从QWidget继承下来的类的实例对象,然后重载这个类的paintEvent函数,在这个函数里面调用QPainter(this)画图。这时候坐标系就会以imageRead的左上角为原点
#3 [mudfish 11-16 17:12]
因为只是绘一幅简单的图,所以我希望不要新定义类了,直接在定义
QPainter p(imageRead);
时把p的painterDevice指定为imageRead,从而实现在QWidget类型的变量imageRead上绘图.
结果失败:(
并且现在还是不明白为什么定义QPainter p(this);就可以在当前form上绘图,
而定义QPainter p(imageRead);却不能在指定的imageRead上绘图?
我现在就是重新定义了一个新类来做的,谢谢tdns:)