如何在单击后更改矩形的颜色
How to change the color of a rectangle after a click?
我编写的代码显示了一个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();
}
}
相关文章:
- QTreeView幻灯片多选后无法使用单击选择
- WinAPI 在单击第一个对话框上的按钮控件并销毁第一个对话框后创建第二个对话框
- QML TableView 使用 QtQuick.Controls 2 单击行
- ImGui 在单击按钮后冻结
- 有没有办法区分Qt小部件是通过鼠标单击还是通过按表键获得焦点?
- 我想使用此代码单击某个特定窗口,但它无法正常工作
- 如何在QSplashScreen中禁用鼠标单击
- 单击一个按钮后创建一个按钮
- C++鼠标单击时的屏幕截图不起作用
- 我的主窗口在创建时或单击更新区域时是否会收到编辑控件?
- 标签检测鼠标单击 c++
- 如何将我的程序添加到文件和文件夹的macOS右键单击菜单?
- 使用 SFML 在矩形的矢量中查找鼠标单击量
- 在单击 QPushButton 时调用带有参数的函数
- 如何在单击按钮FLTK的确切时刻获得小部件的值
- 如何使用鼠标单击选择多个 QLabel 对象?
- WM_PAINT基于按钮单击
- 在使用 c++ 的 win32 api 中,我想跟踪双击和三次单击等
- 单击按钮后对QML矩形的颜色设置动画
- 如何在单击后更改矩形的颜色