子类化QWidget iconEditor实现<三>

来源:互联网 发布:数据段字节变量 编辑:程序博客网 时间:2024/06/07 01:33

接上一章<三>

 这里主要讲述鼠标左键和右键产生相应像素点变黑或者变白的效果即用来设置或者清空一个像素.主要一个是单击和移动时产生的效果

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.

ConstantValueDescriptionQt::NoButton0x00000000The button state does not refer to any button (see QMouseEvent::button()).Qt::LeftButton0x00000001The 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::RightButton0x00000002The right button.Qt::MidButton0x00000004The middle button.Qt::MiddleButtonMidButtonThe middle button.Qt::XButton10x00000008The first X button.Qt::XButton20x00000010The 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来确定是否需要设置像素点。



原创粉丝点击