如何在单击后更改矩形的颜色

How to change the color of a rectangle after a click?

本文关键字:颜色 单击      更新时间:2023-10-16

我编写的代码显示了一个5x5的矩形:

void PrintRectangle::paintEvent(QPaintEvent *)
{
    QPainter p(this);
    int xpos=20;
    int ypos=20;
    int recWidth=50;
    int recHeight=50;
    int y=20;
    for(int i=0; i<5; i++)
    {
        ypos=20;
        p.fillRect(xpos,ypos,recWidth,recHeight,Qt::red);
        for(int j=0; j<5; j++)
        {
           p.fillRect(xpos,ypos,recWidth,recHeight,Qt::red);
           ypos+=60;
        }
        xpos+=60;
    }
}

这很好。如何实现一个功能,改变点击矩形的颜色?我应该把这个矩形存储在一个列表中吗?

你需要重新实现

virtual void    mousePressEvent(QMouseEvent * event)

事件,你可以得到点击的位置,并检查哪些框需要改变颜色。之后,为widget调用update()。

下面的代码将被点击的单元格画成绿色,其他单元格画成红色。

widget.h

#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
class Widget : public QWidget
{
    Q_OBJECT
public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
protected:
    void paintEvent(QPaintEvent *);
    void mousePressEvent( QMouseEvent* ev);
private:
    void resetClickedIndex();
    void updateIndexFromPoint( const QPoint& point);
private:
    int mXIndex;
    int mYIndex;
};
#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include <QPainter>
#include <QMouseEvent>
Widget::Widget(QWidget *parent) :
QWidget(parent)
{
    resetClickedIndex();
}
Widget::~Widget()
{
}
void Widget::paintEvent(QPaintEvent *)
{
    QPainter p(this);
    int xpos=20;
    int ypos=20;
    int recWidth=50;
    int recHeight=50;
    int y=20;
    for(int i=0; i<5; i++)
    {
        ypos=20;
        for(int j=0; j<5; j++)
        {
            QColor color = Qt::red;
            if( i == mXIndex && j == mYIndex )
            {
                color = Qt::green;
            }
           p.fillRect(xpos,ypos,recWidth,recHeight,color);
           ypos+=60;
        }
        xpos+=60;
    }
}
void Widget::mousePressEvent(QMouseEvent *ev)
{
    QPoint point = ev->pos();
    updateIndexFromPoint( point );
    update();
}
void Widget::resetClickedIndex()
{
    mXIndex = -1;
    mYIndex = -1;
}
void Widget::updateIndexFromPoint(const QPoint &point)
{
    int x = point.x() - 20;
    int y = point.y() - 20;
    if( ( (x >= 0 )  && ( x <= 300) ) && ( (y >= 0 )  && ( y <= 300) ) )
    {
        mXIndex = x / 60; //rec width + spacing
        mYIndex = y / 60; //rec height + spacing
    }
    else
    {
        resetClickedIndex();
    }
}