Qt Study Note(5-2)

Event() : 事件处理器,每一个都对应一种类型的事件

When invoking paintEvent()
  • In widget first displaying , system will generate a paint event
  • In adjusting widget size, system will also generate a paint event
  • In widget hiding and emerging, system will paint hiding area
Two methods for painting
QWidget :: update()QWidget::repaint()
paint in next eventimmediately paint
void IconEditor::paintEvent(QPainEvent *event)
{
	QPainter painter(this);
	if (zoom >= 3)
	{
		painter.setPen(palette().foreground().color()); // 使用调色板设置颜色
		for (int i = 0; i <= image.width(); ++i) // vertical line
		{
			painter.drawline(zoom * i, 0, zoom * i, zoom * image.height());  
			/* 左边两个为坐标起点,右边两个为坐标终点 */
			/* Qt窗口部件左上角处的位置坐标为(0,0) */
		}
		for (int j = 0; j <= image.height(); ++j) // horizontal line
		{
			painter.drawline(0, zoom * j, zoom * image.width(), zoom * j);
		}
		for (int i = 0; i < image.width(); ++i)
		{
			for (int j = 0; j < image.height(); ++j)
			{
				QRect rect = pixelRect(i, j);
				if (!event->region().intersect(rect).isEmpty())
				{
					QColor color = QColor::fromRgba(image.pixel(i, j));
					if (color.alpha() < 255) // paint background
						painter.fillRect(rect, Qt::White);
					painter.fillRect(rect, color); // fill rectangular
				}
			}
		}
	}
}

QRect IconEditor::pixelRect(int i, int j) const
{
	if (zoom >= 3)
	{
		return QRect(zoom * i + 1, zoom * j + 1, zoom - 1, zoom - 1);
		// QRect(x, y, width, height)
	}
	else
	{
		return QRect(zoom * i, zoom * j, zoom, zoom);
	}
}
Three Color Groups of Palette(调色板)
  • Active(激活组)
    supply in current active windows’s widgets
  • Inactive(非激活组)
    supply in other window’s widgets
  • Disabled(不可用组)
    supply in disabled widgets
void IconEditor::mousePressEvent(QMouseEvent *event)
{
	if (event->button() == Qt::LeftButton)
	{
		setImagePixel(event->pos(), true);
	}
	else if (event->button() == Qt::RightButton)
	{
		setImagePixel(event->pos(), false);
	}
}

void IconEditor::mouseMoveEvent(QMouseEvent *event)
{
	/*
		若是同时按下多个键,最终结果实际为QMouseEvent::buttons()
		的返回值与鼠标的按键按照位或(|)运算的结果,因此需要
		位与(&)来判断是否按下某个特定键
	*/
	if (event->button() & Qt::LeftButton)
	{
		setImagePixel(event->pos(), true);
	}
	else if (event->button() & Qt::RightButton)
	{
		setImagePixel(event->pos(), false);
	}
}

void IconEditor::setImagePixel(const QPoint &pos, bool opaque) 
{
	int i = pos.x() / zoom;
	int j = pos.y() / zoom;
	
	if (image.rect().contains(i, j))
	{
		if (opaque) // opaque(不透明的)
		{
			image.setPixel(i, j, penColor().rgba());
		}
		else
		{
			image.setPixel(i, j, qRgba(0, 0, 0, 0));
		}

		update(pixelRect(i, j);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值