QPushButton* button = mbar->findChild<QPushButton*>()引发异常
时间: 2024-05-31 22:13:13 浏览: 10
这个异常可能是由于 `mbar` 指针为空或者没有找到一个名为 `QPushButton` 的子控件导致的。建议检查一下 `mbar` 指针是否被正确地初始化,并且确保在调用 `findChild` 函数时传入了正确的参数。另外,你也可以尝试使用 `Q_ASSERT` 宏来进行断言,以确保 `mbar` 不为空,并且确保子控件已经被正确创建和添加到了 `mbar` 控件中。
相关问题
为什么上述代码 QPushButton *button = qobject_cast<QPushButton*>(sender());报错
抱歉,我在之前的回答中犯了一个错误。在槽函数`onButtonPressed()`中,使用`sender()`函数获取发送信号的对象时,需要将其转换为`QObject`指针才能使用`qobject_cast`进行转换。
以下是修正后的代码:
```cpp
void MainWindow::onButtonPressed()
{
QObject *senderObj = sender();
if (QPushButton *button = qobject_cast<QPushButton*>(senderObj)) {
lastMousePos = button->mapToGlobal(QPoint(0, 0));
longPressTimer->start();
}
}
```
在上述代码中,我们首先将`sender()`返回的指针存储在一个`QObject`指针变量`senderObj`中,然后使用`qobject_cast`将其转换为`QPushButton`指针,并将结果赋值给`button`变量。这样,您就可以继续使用`button`来操作相应的按钮。
非常抱歉给您带来的困扰,希望这次能够帮助您解决问题。如果还有其他问题,请随时提问。
QAction *action = qobject_cast<QAction*>(sender()); QMenu *menu = qobject_cast<QMenu*>(action->parent()); QPushButton *button = qobject_cast<QPushButton*>(menu->parent());第三行崩溃
第三行崩溃可能是因为`menu`对象没有正确地获取到,导致无法获取到`button`对象。你可以在第二行代码后添加一些错误处理来排查问题。
以下是一个可能的解决方案:
```
QAction *action = qobject_cast<QAction*>(sender());
QMenu *menu = qobject_cast<QMenu*>(action->parent());
if (!menu) {
qDebug() << "Failed to cast parent of action to QMenu";
return;
}
QPushButton *button = qobject_cast<QPushButton*>(menu->parent());
if (!button) {
qDebug() << "Failed to cast parent of menu to QPushButton";
return;
}
```
这段代码会打印出错误信息并返回,帮助你确定问题所在。你可以根据输出的信息来进一步调试和解决问题。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.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)