qt 怎么获得点击QWdiget时的文本
时间: 2023-07-13 07:25:08 浏览: 91
在 Qt 中,可以通过重载 QWidget 的 `mousePressEvent` 函数来获取鼠标点击事件,并在该函数中获取点击时的文本。具体来说,可以使用 QMouseEvent 类提供的 `pos()` 函数获取鼠标点击的位置,然后使用 `childAt()` 函数获取鼠标点击位置对应的子控件,最后通过子控件的 `text()` 函数获取点击时的文本。
以下是一个示例代码:
```cpp
// 重载 QWidget 的 mousePressEvent 函数
void MyWidget::mousePressEvent(QMouseEvent *event) {
// 获取鼠标点击的位置
QPoint pos = event->pos();
// 获取鼠标点击位置对应的子控件
QWidget *child = childAt(pos);
// 判断子控件是否为 QLabel 类型
if (child && child->inherits("QLabel")) {
// 获取子控件的文本
QString text = static_cast<QLabel*>(child)->text();
// 在这里可以对获取到的文本进行处理
}
// 调用父类的 mousePressEvent 函数
QWidget::mousePressEvent(event);
}
```
在上面的代码中,我们重载了 QWidget 的 `mousePressEvent` 函数,并在该函数中获取鼠标点击事件。首先,我们使用 `pos()` 函数获取鼠标点击的位置,然后使用 `childAt()` 函数获取鼠标点击位置对应的子控件。接下来,我们判断子控件是否为 QLabel 类型,如果是,就使用 `text()` 函数获取子控件的文本。最后,我们可以对获取到的文本进行处理。
阅读全文
相关推荐















