我是Qt的新手。现在我正在尝试制作一个简单的绘图应用程序。
主要想法 - 我在mainwindow中有一个额外的小部件,它有一个QLabel,显示一个QImage(用于绘制像素的画布)。问题是我无法正确设置imgDisplayer标签的大小。它似乎总是比我想要的小,并且有错误的Y坐标。起初我尝试imgDisplayer->setGeometry(0,0, this->width(), this->height());
,但它也没有正常工作(标签非常小)
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);
}
答案 0 :(得分: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);
或者,如果你真的希望imgDisplayer
成为DrawingArea
的直接孩子,你可以覆盖QWidget::resizeEvent
并利用这个机会设置其几何...
void DrawingArea::resizeEvent (QResizeEvent *event) override
{
QWidget::resizeEvent(event);
imgDisplayer->setGeometry(rect());
}