接上一章<三>
这里主要讲述鼠标左键和右键产生相应像素点变黑或者变白的效果即用来设置或者清空一个像素.主要一个是单击和移动时产生的效果
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)
{
if(event->buttons() & Qt::LeftButton) {
setImagePixel(event->pos(),true);
} else if(event->buttons() & Qt::RightButton) {
setImagePixel(event->pos(), false);
}
}
在mousePressEvent()中首先用QMouseEvent创建一个event对象,event->button()返回鼠标按钮事件,通常在鼠标没有按下或者移动时返回的是:Qt::NoButton ,这里我们列出所有的鼠标事件:
This enum type describes the different mouse buttons.
Constant | Value | Description |
---|---|---|
Qt::NoButton | 0x00000000 | The button state does not refer to any button (see QMouseEvent::button()). |
Qt::LeftButton | 0x00000001 | The left button is pressed, or an event refers to the left button. (The left button may be the right button on left-handed mice.) |
Qt::RightButton | 0x00000002 | The right button. |
Qt::MidButton | 0x00000004 | The middle button. |
Qt::MiddleButton | MidButton | The middle button. |
Qt::XButton1 | 0x00000008 | The first X button. |
Qt::XButton2 | 0x00000010 | The second X button. |
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) {
image.setPixel(i, j, penColor().rgba());
} else {
image.setPixel(i, j, qRgba(0, 0, 0, 0));
}
update(pixelRect(i, j));
}
}
const QPoint &pos这里使用引用传参,引用传参是C++里面用的非常多的传参方式,QT也不例外.
使用pos.x() .y()来返回光标的x,y坐标,再除上缩放因子得到图像坐标。rect中构造一个方形的范围,用contains来判断是否在这个构造的范围附近,如果是则返回true.
最好判断opaque来确定是否需要设置像素点。