Qt应用程序中的奇怪错误

Weird bug in Qt application

本文关键字:错误 应用程序 Qt      更新时间:2023-10-16

在我的应用程序中,我重新实现了QGraphicsView检查mouseReleaseEvent(),然后在鼠标所在的位置告诉项目来处理事件。

我的视图QGraphicsItem由另外两个QGraphicsItems组成,我检查正在单击两者中的哪一个(或者更确切地说是释放按钮),并处理相应的事件。

在我的 Widget 的构造函数中,我将其中一个项目设置为默认选中,使用与项目检测到发布时使用的相同方法。

当我调试时,我发现对于LabelItem,构造函数调用 select 没有问题(当我第一次启动应用程序时结果很清楚)。但是,当我单击这些项目时,应用程序终止。我看到我正在进入选择功能,但没有离开它。所以问题就在这里。

这很奇怪,因为选择功能只是一个单行设置器。

void LabelItem::select()
{
    selected = true;
}

这是mouseReleaseEvent;

void LayerView::mouseReleaseEvent(QMouseEvent *event)
{
    LayerItem *l;
    if(event->button() == Qt::LeftButton)
    {           
        l = (LayerItem *) itemAt(event->pos());
        if(l->inLabel(event->pos()))     
        {                                 //No problem upto this point, if label is clicked on
            l->setSelection(true);        //in setSelection, I call select() or unselect() of LabelItem, 
                                          //which is a child of LayerItem, and the problem is there.
                                          //In the constructor for my main widget, I use setSelection
                                          //for the bottom most LayerItem, and have no issues.
            emit selected(l->getId());
        }
            else if(l->inCheckBox(event->pos()))
        {
            bool t = l->toggleCheckState();
            emit toggled(l->getId(), t);
        }
   }
}

当我在函数中注释掉该行时,我没有错误。我还没有调试其他QGraphicsItem CheckBoxItem,但应用程序也会因其事件而终止。我认为这个问题可能是相关的,所以我现在专注于select

我完全不知道是什么原因导致了这种情况以及为什么会发生这种情况。根据我过去的经验,我很确定这是一件简单的事情,我愚蠢地没有想到,但我无法弄清楚是什么。

帮助将不胜感激。

如果LabelItem位于LayerItem的顶部,itemAt很可能会返回LabelItem,因为它是鼠标下最顶层的项目。除非LabelItem设置为不接受任何带有 l->setAcceptedMouseButtons(0) 的鼠标按钮。

尝试使用qgraphicsitem_cast来测试项目的类型。每个派生类都必须重新定义QGraphicsItem::type(),以便强制转换函数能够标识该类型。

您还可以通过重新定义其QGraphicsItem::mouseReleaseEvent()方法来处理项目本身中的单击,这将消除对邪恶强制转换的需求,但您必须删除函数LayerView::mouseReleaseEvent()或至少调用基类实现,QGraphicsView::mouseReleaseEvent(),以允许项目接收事件。

我看到了这些奇怪的行为: 这主要是二进制不兼容 - c ++方面看起来是正确的,崩溃只是没有意义。如您所说:在您的代码中,"选定"变量不能是原因。您是否更改了声明并忘记重新编译所有链接的对象。只需清理并重新编译所有对象文件即可。在 99% 的情况下为我工作。

相关文章: