Qt5连接导致未处理的异常或HEAP损坏

Qt5 connection causes Unhandled Exception or HEAP CORRUPTION

本文关键字:异常 HEAP 损坏 未处理 连接 Qt5      更新时间:2023-10-16

我在VS2010SP1上使用Qt5.5。我在dock小部件中有一个QCheckBox,它控制同一dock小程序中的QTableView(提示到ConsoleWindowView(是否自动滚动。

问题1:

当我将QCheckBox::stateChanged信号连接到QTableView的插槽(autoScroll(时,除非我更改QCheckBox的状态并退出,否则一切似乎都很好。在出口我得到错误:

调试错误!程序:QtTests.exe HEAP CORRUPTION DETECTED:after0x02B63850处的正常块(#4613(。CRT检测到应用程序在堆缓冲区结束后写入内存。

如果我在没有激活QCheckBox的情况下退出,则退出是正常的。

问题2:

考虑到这可能与销毁顺序有关,我试图在QTableView析构函数中"记住"连接和断开连接,但当我试图将QObject::connect的返回值分配给QMetaObject::connection成员变量时,我得到:

QtTests.exe中0x669859c2处未处理的异常:0xC0000005:访问违规写入位置0xabababc7

下面是代码,后面是关联的ui文件。

崩溃的区域在Gui.h中,方法connectControls。对于问题1,配置为:

QObject::connect(AutoScrollCheckBox, &QCheckBox::stateChanged, this, &ConsoleWindowView::autoScroll); // CRASH1: Debug Error! Program: QtTests.exe HEAP CORRUPTION DETECTED: after Normal block (#4613) at 0x02B63850. CRT detected that the application wrote to memory after end of heap buffer.
//QMetaObject::Connection NewConnection = QObject::connect(AutoScrollCheckBox, &QCheckBox::stateChanged, this, &ConsoleWindowView::autoScroll);
//AutoScrollConnection = NewConnection; // CRASH2: Unhandled exception at 0x669859c2 in QtTests.exe: 0xC0000005: Access violation writing location 0xabababc7

对于问题2,配置为:

//QObject::connect(AutoScrollCheckBox, &QCheckBox::stateChanged, this, &ConsoleWindowView::autoScroll); // CRASH1: Debug Error! Program: QtTests.exe HEAP CORRUPTION DETECTED: after Normal block (#4613) at 0x02B63850. CRT detected that the application wrote to memory after end of heap buffer.
QMetaObject::Connection NewConnection = QObject::connect(AutoScrollCheckBox, &QCheckBox::stateChanged, this, &ConsoleWindowView::autoScroll);
AutoScrollConnection = NewConnection; // CRASH2: Unhandled exception at 0x669859c2 in QtTests.exe: 0xC0000005: Access violation writing location 0xabababc7

main.cpp

#include <QtWidgets/QApplication>
#include "Gui.h"
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Gui w;
    w.show();
    return a.exec();
}

#ifndef QTTESTS_H
#define QTTESTS_H
#include <iostream>
#include <QTimer>
#include <QHeaderView>
#include <QCheckBox>
#include <QObject>
#include "ui_Gui.h"
class ConsoleWindowModelClass : public QAbstractTableModel
{
    Q_OBJECT
public:
    ConsoleWindowModelClass(QObject *parent)
        : QAbstractTableModel(parent)
        , RowCount(0)
    {
        //
        ControllerTimer = new QTimer(this);
        connect(ControllerTimer, SIGNAL(timeout()), this, SLOT(updateController()));
        ControllerTimer->start(2000);
    }
    int rowCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE
    {
        return RowCount;
    }
    int columnCount(const QModelIndex &parent = QModelIndex()) const Q_DECL_OVERRIDE
    {
        return 2;
    }
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const Q_DECL_OVERRIDE
    {
        if (role == Qt::DisplayRole)
        {
            return QString("Row%1, Column%2")
                .arg(index.row() + 1)
                .arg(index.column() +1);
        }
        return QVariant();
    }
    QVariant headerData(int section, Qt::Orientation orientation, int role) const Q_DECL_OVERRIDE
    {
        if (orientation == Qt::Horizontal)
        {
            if (role == Qt::DisplayRole)
            {
                switch(section)
                {
                case 0:
                    return "Stamp";
                    break;
                case 1:
                    return "Text";
                    break;
                default:
                    return QString("Column %1").arg(section + 1);
                    break;
                }
            }
        }
        else if (orientation == Qt::Vertical)
        {
            if (role == Qt::DisplayRole)
            {
                return QString("%1").arg(section + 1);
            }
        }
        return QVariant();
    }
protected:
    unsigned int RowCount;
    QTimer *ControllerTimer;
    private slots:
        // GUI triggered
        // Timer triggered
        void updateController()
        {
            beginInsertRows(QModelIndex(), RowCount, RowCount);
            RowCount++;
            endInsertRows();
        }
};
class ConsoleWindowView : public QTableView
{
    Q_OBJECT
public:
    ConsoleWindowView(QWidget *parent = 0)
        : QTableView(parent)
        , AutoScroll(true)
    {
    }
    virtual ~ConsoleWindowView()
    {
        //disconnect(AutoScrollConnection);
    }
    void setTheModel(QAbstractItemModel *TheModel)
    {
        QTableView::setModel(TheModel);
        connect(model(), &QAbstractItemModel::rowsInserted, this, &ConsoleWindowView::modelRowsInserted);
    }
    void connectControls(QCheckBox *AutoScrollCheckBox, QCheckBox *ReverseList, QPushButton *MarkerA, QPushButton *MarkerB, QPushButton *MarkerC, QPushButton *MarkerD)
    {
        try
        {
            //QObject::connect(AutoScrollCheckBox, &QCheckBox::stateChanged, this, &ConsoleWindowView::autoScroll); // CRASH1: Debug Error! Program: QtTests.exe HEAP CORRUPTION DETECTED: after Normal block (#4613) at 0x02B63850. CRT detected that the application wrote to memory after end of heap buffer.
            QMetaObject::Connection NewConnection = QObject::connect(AutoScrollCheckBox, &QCheckBox::stateChanged, this, &ConsoleWindowView::autoScroll);
            AutoScrollConnection = NewConnection; // CRASH2: Unhandled exception at 0x669859c2 in QtTests.exe: 0xC0000005: Access violation writing location 0xabababc7
        }
        catch (const std::exception &Exception)
        {
            std::cerr << "ConsoleWindowView::connectControls: " << Exception.what() << std::endl;
        }
    }
    public slots:
        void modelRowsInserted(const QModelIndex & parent, int start, int end)
        {
            if (model() != nullptr)
            {
                if (AutoScroll)
                {
                    scrollTo(model()->index(start, 0));
                }
            }
        }
        void autoScroll(int State)
        {
            if (State == 0)
            {
                AutoScroll = false;
            }
            else
            {
                AutoScroll = true;
            }
        }
signals:
protected:
    bool AutoScroll;
    QMetaObject::Connection AutoScrollConnection;
private:
};
class Gui : public QMainWindow
{
    Q_OBJECT
public:
    Gui(QWidget *parent = 0);
    ~Gui();
protected:
    ConsoleWindowModelClass *ConsoleWindowModel;
private:
    Ui::Gui ui;
    void createConsoleWindow();
    //
private slots:
    // GUI triggered
};
#endif // QTTESTS_H

桂.cpp

#include <iostream>
#include <QTimer>
#include <QHeaderView>
#include <QCheckBox>
#include <QObject>
// Qt model handling the BusSimLowRateTx message from BusSim to DataSwitch.
#include <QAbstractTableModel>
#include "Gui.h"
Gui::Gui(QWidget *parent)
    : QMainWindow(parent)
{
    // create UI
    ui.setupUi(this);
    //
    ui.actionExit->setShortcuts(QKeySequence::Quit);
    ui.actionExit->setStatusTip(tr("Exit the application"));
    connect(ui.actionExit, SIGNAL(triggered()), this, SLOT(close()));
    // create models
    ConsoleWindowModel = new ConsoleWindowModelClass(this); // should be deleted as part of QMainWindow destructor, by specifying this as the parent.
    //
    // connect ConsoleWindowModel to the View(s)
    createConsoleWindow();
}
Gui::~Gui()
{
    // ConsoleWindowModel - should be deleted as part of QMainWindow destructor.
    //ConsoleWindowView *View = static_cast<ConsoleWindowView *>(ui.ConsoleOutputTable);
    //disconnect(ui.AutoScroll, &QCheckBox::stateChanged, View, &ConsoleWindowView::autoScroll);
}
void Gui::createConsoleWindow()
{
    ConsoleWindowView *View = static_cast<ConsoleWindowView *>(ui.ConsoleOutputTable);
    View->setTheModel(ConsoleWindowModel);
    for (int c = 1; c < View->horizontalHeader()->count(); ++c)
    {
        View->horizontalHeader()->setSectionResizeMode(c, QHeaderView::Stretch);
    }
    // connect the other ConsoleWindow Controls to the model
    View->connectControls(ui.AutoScroll, ui.NewestAtTop, ui.MarkerA, ui.MarkerB, ui.MarkerC, ui.MarkerD);
}

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Gui</class>
 <widget class="QMainWindow" name="Gui">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>593</width>
    <height>652</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Gui Tests</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <property name="sizePolicy">
    <sizepolicy hsizetype="Maximum" vsizetype="Preferred">
     <horstretch>0</horstretch>
     <verstretch>0</verstretch>
    </sizepolicy>
   </property>
   <layout class="QGridLayout" name="gridLayout_7"/>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>593</width>
     <height>21</height>
    </rect>
   </property>
   <widget class="QMenu" name="menuFile">
    <property name="title">
     <string>File</string>
    </property>
    <addaction name="actionExit"/>
   </widget>
   <widget class="QMenu" name="menuView">
    <property name="title">
     <string>View</string>
    </property>
   </widget>
   <addaction name="menuFile"/>
   <addaction name="menuView"/>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
  <widget class="QDockWidget" name="ConsoleOutput">
   <property name="windowTitle">
    <string>Console Output</string>
   </property>
   <attribute name="dockWidgetArea">
    <number>8</number>
   </attribute>
   <widget class="QWidget" name="ConsoleOutputDock">
    <layout class="QGridLayout" name="gridLayout_4">
     <item row="0" column="0">
      <layout class="QGridLayout" name="gridLayout">
       <item row="0" column="0">
        <layout class="QHBoxLayout" name="horizontalLayout">
         <item>
          <widget class="QCheckBox" name="AutoScroll">
           <property name="text">
            <string>Auto Scroll</string>
           </property>
           <property name="checked">
            <bool>true</bool>
           </property>
          </widget>
         </item>
         <item>
          <widget class="QCheckBox" name="NewestAtTop">
           <property name="text">
            <string>Newest At Top</string>
           </property>
          </widget>
         </item>
         <item>
          <widget class="QPushButton" name="MarkerA">
           <property name="styleSheet">
            <string notr="true">background-color: rgb(255, 0, 0);</string>
           </property>
           <property name="text">
            <string>Marker A</string>
           </property>
          </widget>
         </item>
         <item>
          <widget class="QPushButton" name="MarkerB">
           <property name="styleSheet">
            <string notr="true">background-color: rgb(0, 255, 0);</string>
           </property>
           <property name="text">
            <string>Marker B</string>
           </property>
          </widget>
         </item>
         <item>
          <widget class="QPushButton" name="MarkerC">
           <property name="styleSheet">
            <string notr="true">background-color: rgb(255, 255, 0);</string>
           </property>
           <property name="text">
            <string>Marker C</string>
           </property>
          </widget>
         </item>
         <item>
          <widget class="QPushButton" name="MarkerD">
           <property name="styleSheet">
            <string notr="true">background-color: rgb(0, 0, 255);
color: rgb(255, 255, 255);</string>
           </property>
           <property name="text">
            <string>Marker D</string>
           </property>
          </widget>
         </item>
        </layout>
       </item>
       <item row="1" column="0">
        <widget class="QTableView" name="ConsoleOutputTable"/>
       </item>
      </layout>
     </item>
    </layout>
   </widget>
  </widget>
  <action name="actionExit">
   <property name="text">
    <string>Exit</string>
   </property>
  </action>
  <action name="actionECIO_Outputs">
   <property name="text">
    <string>Enlightenment Monitor</string>
   </property>
  </action>
  <action name="actionECIO_Inputs">
   <property name="text">
    <string>Enlightenment Control</string>
   </property>
  </action>
  <action name="actionSHM_Control">
   <property name="text">
    <string>SHM Input</string>
   </property>
  </action>
  <action name="actionSHM_Output">
   <property name="text">
    <string>SHM Output</string>
   </property>
  </action>
  <zorder>ConsoleOutput</zorder>
 </widget>
 <resources/>
 <connections/>
</ui>

您正在静态地将QTableView的实例强制转换为ConsoleWindowView。它不会起作用,因为它不是ConsoleWindowView。你期待什么?你为什么static_cast

如果您不确定静态转换是否有效,请使用qobject_cast。它会失败,产生一个nullptr结果,并且您知道必须停下来找出为什么没有得到正确的类实例。你并不是因为你的UI文件坏了——你必须在UI文件中有正确类型的实例。

修复UI文件以实例化正确的类:

  1. 右键单击设计视图中的ConsoleOutputTable
  2. 单击升级到…
  3. 提升类名:中输入ConsoleWindowView
  4. 头文件中输入gui.h
  5. 单击添加
  6. 单击升级

在任何情况下,都不需要手动跟踪对象连接。

其他点/咆哮:

  1. 如果你想要一个定时器实例,只需在那里放一个QTimer成员——使用指针并通过间接引用和额外的堆分配过早地进行悲观化有什么意义?让你的生活变得轻松。

  2. 抽象项视图已具有名为autoScroll的属性。你为一处新房产取了一个相同的名字,这让每个人的生活都变得可怕。给它起个别的名字,比如scrollToNewest

  3. 您的自动滚动表视图应该具有一个控制其行为的属性。然后,您可以将该属性连接到某个位置的控件,在该位置可以了解诸如复选框之类的源控件。将视图与一些随机控件紧密绑定是个坏主意。这种看法应该是一般性的。使用它的窗体了解其他控件,并知道如何将视图绑定到这些控件。

  4. CCD_ 11是一种虚拟方法。覆盖它,不要创建自己的。

  5. 如果变量名以大写字母开头,你会把自己弄糊涂。不要那样做。类以大写字母开头,变量和成员以小写字母开头。

  6. signalsslots部分宏的使用应该仅在信号和/或时隙在逻辑上相关并且它们有很多的情况下使用——太多了,以至于Q_SIGNALQ_SLOT前缀的使用会有点多。在大多数情况下,您有一些信号/插槽,因此应该使用前缀。然后,您可以很容易地将信号和插槽声明与其他相关方法进行分组,以便声明的分组遵循函数,而不是实现细节。

  7. 在Qt5中,您根本不需要Q_SLOT前缀,任何方法都可以是具有新connect语法的槽。如果希望方法的元数据在运行时可用,则只需要Q_SLOTQ_INVOKABLE前缀。

考虑到以上内容,ConsoleWindowView类应该是这样的:

class ConsoleWindowView : public QTableView
{
   Q_OBJECT
   Q_PROPERTY(bool scrollToNewest READ scrollToNewest WRITE setScrollToNewest)
   bool m_scrollToNewest;
   void modelRowsInserted(const QModelIndex &, int start, int end) {
      Q_UNUSED(end)
      if (model() && m_scrollToNewest) scrollTo(model()->index(start, 0));
   }
public:
   ConsoleWindowView(QWidget *parent = 0) : QTableView(parent), m_scrollToNewest(true)
   {}
   void setModel(QAbstractItemModel *TheModel) Q_DECL_OVERRIDE
   {
      QTableView::setModel(TheModel);
      connect(model(), &QAbstractItemModel::rowsInserted, this, &ConsoleWindowView::modelRowsInserted);
   }
   Q_SLOT void setScrollToNewest(bool s) { m_scrollToNewest = s; }
   bool scrollToNewest() const { return m_scrollToNewest; }
};

Gui类,在将控制台视图与用于调整它的具体控件解耦后:

class Gui : public QMainWindow
{
   Q_OBJECT
   Ui::Gui ui;
   ConsoleWindowModel consoleWindowModel;
   void connectConsoleWindow() {
      auto view = ui.ConsoleOutputTable;
      view->setModel(&consoleWindowModel);
      for (int c = 1; c < view->horizontalHeader()->count(); ++c)
         view->horizontalHeader()->setSectionResizeMode(c, QHeaderView::Stretch);
      connect(ui.AutoScroll, &QCheckBox::toggled, view, &ConsoleWindowView::setScrollToNewest);
   }
public:
   Gui(QWidget *parent = 0) : QMainWindow(parent) {
      ui.setupUi(this);
      ui.actionExit->setShortcuts(QKeySequence::Quit);
      ui.actionExit->setStatusTip(tr("Exit the application"));
      connect(ui.actionExit, &QAction::triggered, this, &QWidget::close);
      connectConsoleWindow();
   }
};

请注意,我们只是根据connectConsoleWindow方法的作用来命名。您错误地将其命名为createConsoleWindow,然后对其行为发表了评论,即它不创建任何内容,只连接内容这是一个可怕的反模式,必须被视为即时代码审查失败。在可行的情况下,根据他们所做的事情命名(就在这里(。使代码自我文档化。

最后,这就是您应该实例化长寿命成员(如定时器等(的方法,而不使用原始指针和显式内存分配,这会导致人为错误:

class ConsoleWindowModel : public QAbstractTableModel
{
   Q_OBJECT
   unsigned int m_rowCount;
   QTimer m_controllerTimer;
   void updateController()
   {
      beginInsertRows(QModelIndex(), m_rowCount, m_rowCount);
      m_rowCount++;
      endInsertRows();
   }
public:
   ConsoleWindowModel(QObject *parent = 0)
      : QAbstractTableModel(parent)
      , m_rowCount(0) {
      connect(&m_controllerTimer, &QTimer::timeout, this, &ConsoleWindowModel::updateController);
      m_controllerTimer.start(2000);
   }
   [...]