gpt4 book ai didi

c++ - Qt5 连接导致 Unhandled Exception 或 HEAP CORRUPTION

转载 作者:行者123 更新时间:2023-11-30 01:47:11 26 4
gpt4 key购买 nike

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

问题一:

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

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.



如果我没有激活QCheckBox就退出了,退出是正常的。

问题2:

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

Unhandled exception at 0x669859c2 in QtTests.exe: 0xC0000005: Access violation writing location 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

主.cpp
#include <QtWidgets/QApplication>

#include "Gui.h"

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Gui w;
w.show();
return a.exec();
}

贵.h
#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

gui.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);
}

贵.ui
<?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 文件以实例化正确的类:

  • 在设计 View 中右键单击 ConsoleOutputTable。
  • 点击推广到....
  • 输入 ConsoleWindowView在升级类名中:。
  • 输入 gui.h在头文件中:.
  • 单击添加。
  • 点击推广。

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

    其他观点/咆哮:
  • 如果你想要一个计时器实例,只需放一个 QTimer那里的成员 - 使用指针并通过间接引用和额外的堆分配过早地悲观有什么意义?让您的生活轻松。
  • 抽象项目 View 已经有一个名为 autoScroll 的属性。 .你把一个新属性(property)的同名弄乱了,让每个人的生活都变得糟糕透顶。将其命名为其他名称,例如 scrollToNewest .
  • 你的自动滚动 TableView 应该有一个属性来控制它的行为。然后,您可以将该属性连接到一个有助于了解源控件(如复选框)的位置的控件。将 View 紧密绑定(bind)到一些随机控件是一个坏主意。观点应该是一般的。您使用它的表单了解其他控件,并且知道如何将 View 绑定(bind)到这些控件。
  • setModel是一种虚方法。覆盖它,不要创建自己的。
  • 变量名以大写字母开头会让你感到很困惑。不要那样做。类以大写字母开头,变量和成员以小写字母开头。
  • 使用signalsslots仅当信号和/或插槽在逻辑上相关并且其中有很多时才应使用节宏 - 太多了,使用 Q_SIGNALQ_SLOT前缀会有点多。在大多数情况下,您有少量信号/插槽,您应该使用前缀。然后,您可以轻松地将信号和槽声明与其他相关方法分组,以便声明分组遵循函数,而不是实现细节。
  • 在 Qt 5 中,您不需要 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类,在将控制台 View 与用于调整它的具体控件解耦之后:
    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);
    }
    [...]

    关于c++ - Qt5 连接导致 Unhandled Exception 或 HEAP CORRUPTION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31918194/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com