使用QT QPainter画一面彩色墙
效果
定义一个颜色表
static const QRgb colorTable[8] = {
0xFFA500, 0xCC6666, 0x66CC66, 0x6666CC,
0xCCCC66, 0xCC66CC, 0x66CCCC, 0xDAAA00
};
定义砖块宽度高度
private:
Ui::RainbowWidget *ui;
enum { BrickWidth =80, BrickHeight = 40 };
int col() { return contentsRect().width() / BrickWidth +1 ; }
int row() { return contentsRect().height() / BrickHeight +1; }
void drawBrick(QPainter &painter, int x, int y, int colorIndex);
画砖块形状
void RainbowWidget::drawBrick(QPainter &painter, int x, int y, int colorIndex)
{
QColor color = colorTable[colorIndex];
painter.fillRect(x + 1, y + 1,BrickWidth - 2, BrickHeight - 2,
color);
painter.setPen(color.light());
painter.drawLine(x, y + BrickHeight - 1, x, y);
painter.drawLine(x, y, x +BrickWidth - 1, y);
painter.setPen(color.dark());
painter.drawLine(x + 1, y + BrickHeight - 1,
x + BrickWidth - 1, y + BrickHeight - 1);
painter.drawLine(x + BrickWidth - 1, y + BrickHeight- 1,
x + BrickWidth - 1, y + 1);
}
使用图片加载为窗口背景
RainbowWidget::RainbowWidget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::RainbowWidget)
{
ui->setupUi(this);
QRect rect = contentsRect();
QPixmap pixmap(rect.width() ,rect.height());
QPainter painter(&pixmap);
QColor color=RGB(100,0,0);
painter.fillRect(pixmap.rect(), color);
//painter.fillRect(rect, color);
for (int i = 0; i < row(); ++i) {
// int spacing=(qrand() % 33 + 1) ;
for (int j = 0; j < col(); ++j) {
int colorIndex=qrand() % 7 + 1;
if (i%2 !=0){
drawBrick(painter, j * BrickWidth, i * BrickHeight, colorIndex);
}else{
drawBrick(painter, j * BrickWidth-(BrickWidth/2 ) , i * BrickHeight, colorIndex);
// drawBrick(painter, j * BrickWidth-50 , i * BrickHeight, shape1);
// drawBrick(painter, j * BrickWidth-spacing , i * BrickHeight, shape1);
}
}
}
//pixmap.save("wall.png");
//背景
QPalette palette = this->palette();
palette.setBrush(QPalette::Window,QBrush(pixmap));
this->setPalette(palette);
}
在这里我们可以学习到如何将图画到QPixmap上,并可以将QPixmap存为文件,这个加载背景的方式不像使用paintEvent会在窗口变化时动态刷新,应该会比paintEvent损耗资源少一些
知道在不使用paintEvent的情况下如何画图并QWidget上显示出来
在使用QT绘图QPainter对象时,发现QT在窗口QWidget画图大部分例子都是在paintEvent上进行的,如果要在别的地方画,在一个Label上画该如何做呢?
这先画到QPixmap,再以背景形式加载也是一个变通方式
QLabel *lb=ui->label;
lb->setPixmap(pixmap);
标签:pixmap,QT,BrickWidth,int,彩色,color,QPainter,painter,BrickHeight
From: https://blog.51cto.com/u_12668715/7418022