'QObject'是'Recorder'的模糊基础

时间:2014-07-11 11:54:49

标签: c++ qt qthread qtcore qobject

我试图在我新创建的类中使用继承QObject的QTimer。但是我试试看,我一直收到错误' QObject'是#Recorder' 的模糊基础。我尽力避免在我的简单程序中出现歧义,但仍然坚持使用它。 这是我班级的结构。

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

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

    return a.exec();
}

dialog.h:mainwindow UI

#ifndef DIALOG_H
#define DIALOG_H

#include "detector.h"
#include <QDialog>
#include <QtCore>

namespace Ui {
class Dialog;
}

class Dialog : public QDialog
{
    Q_OBJECT

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

private:
    Ui::Dialog *ui;
    Detector myDetector;

detector.h:探测器窗口UI

#ifndef DETECTOR_H
#define DETECTOR_H

#include <QDialog>
#include <QtCore>
#include <QObject>
#include "actualrec.h"

namespace Ui {
class Detector;
}

class Detector : public QDialog
{
    Q_OBJECT

public:
    explicit Detector(QWidget *parent = 0);
    ~Detector();
    void run();

private:
    ActualRec theDetector;
    Ui::Detector *ui;

actualrec.h:探测器代码

#ifndef ACTUALREC_H
#define ACTUALREC_H

#include <QtCore>
#include <QObject>    
#include <QImage>
#include "recorder.h"

class ActualRec : public QThread
{
public:
    ActualRec();
    void run();

private:        
    Recorder theRecorder;

recorder.h:记录器代码,我想使用我的QTimer

#ifndef RECORDER_H
#define RECORDER_H

#include <QtCore>

class Recorder : public QThread, public QObject
{

public:
    Recorder();
    void run();

private:
    QTimer* theTimer;

recorder.cpp构造函数有

 *theTimer = new QTimer(this);

输出如下: http://i.imgur.com/Awb6qhd.png

非常感谢任何帮助

3 个答案:

答案 0 :(得分:3)

您的代码中存在几个问题:

1)使用Qt错误使用线程

class Recorder : public QThread, public QObject

a)在没有显式继承QObject的情况下继承QThread就足够了,因为QThread继承了QObject。

b)即使你这样做,从历史上看,QObject应该是一般情况下列表中的第一个基础。

c)但是,您可能希望重新考虑如何使用您的线程。这是一种方式,但必然是最好的。

2)在堆上为QTimer分配对象

为什么首先在堆上为计时器分配内存?可以在堆栈上分配它,特别是因为它是成员。这样,您也不需要处理this麻烦。整个内存管理变得更加简单。

3)不使用Q_NULLPTR

您应该使用它而不是0来表示父母的默认值。

4)包括整个QtCore模块

#include <QtCore>

您应该只包含最终使用的部分。这是一种包含事物的蛮力方式。

因此,请写下这样的内容:

class Recorder : public QThread
{

public:
    Recorder();
    void run();

private:
    QTimer theTimer;

当然,如果你在Qt中反过来使用线程机制,那么为继承编写它是完全没问题的:

class Recorder : public QObject

但是你的代码需要进行一些其他更改,因此无论如何,代码都会被破坏。

答案 1 :(得分:2)

QThread已经继承了QObject,你不能从两个继承QObject的类继承。

答案 2 :(得分:1)

你不应该继承QObject两次。这是因为信号和槽由整数映射,并且id可能与每个碰撞。

这也适用于从QObject继承的任何对象。

class BadClass : public QTimer, public Dialog
{
};
相关问题