2017-06-01 176 views
0

我是Qt的新手。現在我正在嘗試繪製一個簡單的應用程序。 主要思想 - 我在mainwindow中有一個額外的小部件,它有一個QLabel,顯示一個QImage(我的畫布用於繪製像素)。問題是我無法正確設置imgDisplayer標籤的大小。它總是比我想要的要小,並且Y座標錯誤。起初我想imgDisplayer->setGeometry(0,0, this->width(), this->height());,但它並沒有正常工作,以及(標籤是非常小的)無法正確確定QLabel的尺寸

MainWindow.cpp

MainWindow::MainWindow(QWidget *parent) : 
QMainWindow(parent), 
ui(new Ui::MainWindow) 
{ 
ui->setupUi(this); 

area = new DrawingArea(this); 
area->setGeometry(0,0,this->width(),this->height()/2); 
area->show(); 

button = new QPushButton("Draw", this); 
int bwidth = 100, bheight = 50; 
button->setGeometry(200, 300, bwidth, bheight); 
connect(button, SIGNAL(clicked(bool)), this, SLOT(getPoint())); 
} 

DrawingArea.cpp

DrawingArea::DrawingArea(QWidget *parent) : QWidget(parent) 
{ 
setBackgroundRole(QPalette::Base); 
setAutoFillBackground(true); 

canvas = new QImage(300, 300, QImage::Format_RGB32); 
QRgb val = qRgb(189,149,39); 
canvas->fill(Qt::gray); 
canvas->setPixel(4,4,val); 
canvas->setPixel(5,4,val); 


imgDisplayer = new QLabel(this); 
imgDisplayer->setGeometry(0, 0, parent->width(), parent->height()); 
imgDisplayer->setPixmap(QPixmap::fromImage(*canvas)); 
imgDisplayer->show(); 

displayer = new QLabel(this); 
} 

Screenshot

回答

0

最簡單的解決方案是使用layout來管理子窗口小部件...

/* 
* Create the QLabel and set its pixmap. 
*/ 
imgDisplayer = new QLabel; 
imgDisplayer->setPixmap(QPixmap::fromImage(*canvas)); 

/* 
* Create the layout and add imgDisplayer to it. 
*/ 
auto *layout = new QHBoxLayout(this); 
layout->addWidget(imgDisplayer); 

或者,如果你真的想imgDisplayerDrawingArea的直接孩子,你可以覆蓋QWidget::resizeEvent,並利用這個機會來設置它的形狀......

void DrawingArea::resizeEvent (QResizeEvent *event) override 
{ 
    QWidget::resizeEvent(event); 
    imgDisplayer->setGeometry(rect()); 
}