使用qt做一个添加矩形的回调事件
时间: 2023-05-18 18:07:31 浏览: 45
可以使用Qt的QPainter类来实现添加矩形的回调事件。首先,在QWidget的paintEvent()函数中创建一个QPainter对象,然后使用drawRect()函数绘制矩形。接着,在QWidget的mousePressEvent()函数中获取鼠标点击的位置,然后使用QPainter的drawRect()函数绘制矩形。最后,在QWidget的resizeEvent()函数中重新绘制所有的矩形。以下是示例代码:
void MyWidget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.setPen(Qt::black);
painter.setBrush(Qt::NoBrush);
for (const QRect &rect : m_rects) {
painter.drawRect(rect);
}
}
void MyWidget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
QRect rect(event->pos(), QSize(50, 50));
m_rects.append(rect);
update(rect);
}
}
void MyWidget::resizeEvent(QResizeEvent *event)
{
update();
}
相关推荐
![tar](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)