在Qt中,我有一个宽度为5像素,高度为4像素的Qpixmap,我用宽度为.08和高度为.08的矩形填充它,但形成的矩形与我给出的尺寸不同。 我想画出等长的黑色和白色矩形
QLabel *a=new QLabel();
QPixmap b(5,4);
a->setFixedSize(b.size());
QPainter painter(&b);
heightOfCheckeredBox=.08;
widthOfCheckeredBox=.08;
bool switchBetweenBlackAndWhiteBoxRowDirection=true;
int switchBetweenBlackAndWhiteBoxColumnDirection=0;
for(qreal i=0;i<4;i+=heightOfCheckeredBox)
{
for(qreal j=0;j<5;j+=widthOfCheckeredBox)
{
if(switchBetweenBlackAndWhiteBoxRowDirection)
{
painter.setPen(Qt::white);
painter.setBrush(Qt::white);
switchBetweenBlackAndWhiteBoxRowDirection=false;
}
else
{
painter.setPen(Qt::gray);
painter.setBrush(Qt::gray);
switchBetweenBlackAndWhiteBoxRowDirection=true;
}
QRectF rectangle(j,i,widthOfCheckeredBox,heightOfCheckeredBox);
painter.drawRect(rectangle);
}
switchBetweenBlackAndWhiteBoxColumnDirection++;
if(int(switchBetweenBlackAndWhiteBoxColumnDirection)%2==0)
switchBetweenBlackAndWhiteBoxRowDirection=true;
else
switchBetweenBlackAndWhiteBoxRowDirection=false;
}
a->setPixmap(b);
a->show();
答案 0 :(得分:0)
由于您在没有抗锯齿的情况下进行绘制,因此微小的像素大小毫无意义 - 您的期望是什么?
像素图的大小以像素为单位。您的像素图包含5x4 = 20像素。你试图在它上画20个矩形。为此,每个矩形必须是正好一个像素宽和高的正方形。唉,你试图绘制比像素小12.5倍的正方形。这没有多大意义,我不知道你从哪里得到0.08的价值。只需绘制一个像素宽的正方形。
示例:
// https://github.com/KubaO/stackoverflown/tree/master/questions/checkered-paint-42205180
#include <QtWidgets>
QPixmap checkers(const QSizeF & rectSize, const QSize & pixmapSize) {
QPixmap pixmap{pixmapSize};
QPainter painter{&pixmap};
painter.setPen(Qt::NoPen);
const QColor colors[] = {Qt::white, Qt::black};
QPointF pos{};
bool oddRow{}, color{};
while (pos.y() < pixmap.height()) {
painter.setBrush(colors[color ? 1 : 0]);
painter.drawRect({pos, rectSize});
color = !color;
pos.setX(pos.x() + rectSize.width());
if (pos.x() >= pixmap.width()) {
pos.setX({});
pos.setY(pos.y() + rectSize.height());
oddRow = !oddRow;
color = oddRow;
}
}
return pixmap;
}
int main(int argc, char ** argv) {
QApplication app{argc, argv};
QLabel label;
auto pix = checkers({1, 1}, {60, 30});
label.resize(200, 200);
label.setAlignment(Qt::AlignCenter);
label.setPixmap(pix);
label.show();
return app.exec();
}