SIGNAL未发出

时间:2015-08-04 09:18:17

标签: c++ qt qt5.4

我遇到SIGNAL未发出的问题。以下是此问题的最小示例:

main.cpp - 标准主要

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QVBoxLayout>
#include "combobox.h"

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    QWidget *mainWidget = new QWidget;
    setCentralWidget(mainWidget);
    QVBoxLayout *mainLayout = new QVBoxLayout;
    combobox combo_box;
    mainLayout->addWidget(combo_box.box);
    mainWidget->setLayout(mainLayout);
}

MainWindow::~MainWindow()
{

}

combobox.h

#ifndef COMBOBOX_H
#define COMBOBOX_H

#include <QComboBox>
#include <QDebug>

class combobox : public QWidget
{
    Q_OBJECT

public:
    combobox();
    ~combobox();

    QComboBox *box = new QComboBox;

public slots:
    void selection_changed();
};

#endif // COMBOBOX_H

combobox.cpp

#include "combobox.h"

combobox::combobox()
{
    QString string = "test 1";
    box->addItem(string);
    string = "test 2";
    box->addItem(string);
    box->setCurrentIndex(0);
    connect(box, SIGNAL(currentIndexChanged(int)), this, SLOT(selection_changed()));
}

combobox::~combobox()
{

}

void combobox::selection_changed()
{
    qDebug() << "Selection changed";
    box->setCurrentIndex(-1);
}

您需要在编译之前运行qmake。

当我运行此程序并更改组合框索引时,不执行selection_changed。为什么呢?

SIGNAL和SLOT连接肯定有效,因为如果我添加box-&gt; setCurrentIndex(1);在组合框构造函数的末尾,selection_changed将执行一次。

我正在使用QT 5.4与QT Creator

提前致谢!

1 个答案:

答案 0 :(得分:4)

这个问题是因为你在堆栈中创建了ComboBox类对象。因此,如果您在此类的析构函数中编写一些调试信息,您可以在MainWindow构造函数超出范围后立即看到对象被销毁:

ComboBox::~ComboBox()
{
    qDebug() << Q_FUNC_INFO;
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    setupUi(this);


    QWidget *mainWidget = new QWidget;
    setCentralWidget(mainWidget);
    QVBoxLayout *mainLayout = new QVBoxLayout;
    ComboBox combo_box;
    mainLayout->addWidget(combo_box.box);
    mainWidget->setLayout(mainLayout);

    qDebug() << Q_FUNC_INFO;
}

qDebug()得到以下结果:

  

MainWindow :: MainWindow(QWidget *)

     

虚拟ComboBox :: ~ComboBox()

这就是为什么信号不会发出。所以你需要在堆上创建对象或制作一些技巧。

,您已在*box类动态分配了对象ComboBox,并且没有指定此对象的父级,因此似乎可能发生内存泄漏。在ComboBox类的析构函数中指定父对象或删除对象。

相关问题