简体   繁体   中英

Subclassing QIODevice by overriding non-virtual methods

I would like to subclass from QIODevice since I'm creating my custom device (a custom serial port object).

I see that:

writeData(const char *, qint64 ) : qint64
readData(char *, qint64 ) : qint64

are declared as virtual in QIODevice interface, but not the methods:

read(char *, qint64 ) : qint64
write(const char *, qint64 ) : qint64

Then in my project I have a serial port manager class like this:

class SerialPortManager{
public:
    SerialPortManager(int type){
         if (type == 1)
             genericSerialPort = new QSerialPort(); //QT framework
         else if (type == 2)
             genericSerialPort = new MySerialPort(); //my custom object, derived from QIODevice
    }

    qint64 write(char * data, qint64 size)
    {
        genericSerialPort->write(data, size);
    }    

private:
    QIODevice* genericSerialPort = 0;
};

And my custom serial port (MySerialPort.h) defined like this:

class MySerialPort : public QIODevice{
    Q_OBJECT
    public:
        explicit MySerialPort(QObject *parent = Q_NULLPTR);
        virtual ~MySerialPort();

        qint64 readData(char *data, qint64 maxSize);
        qint64 writeData(const char *data, qint64 maxSize);

        qint64 write(char * data, qint64 size);

        ...
    };

What's happening here is that if I create a SerialPortManager object of type 1 ( QSerialPort instance) and I call write on it, the write function on QSerialPort is called. Instead, if I create a SerialPortManager object of type 2 ( MySerialPort instance) and I call write on it, I don't get my write function called.

So, is it possible to override the non-virtual method write of QIODevice ? Otherwise, how can I create a custom QIODevice if write and read are not virtual?

This is done by design. If write and read are not virtual they are not meant to be overridden.

readData and writeData are pure virtual and protected. So I would assume write and read will call these internally.

As to why they are not overridable you have to ask the Qt Designers. It is most likely they modify some internal states etc. which are private so it has to be wrapped in those calls.

Usually Qt classes are pretty well designed so I assume you should not need to override write and read in the first place. If you do there maybe some issue with your design.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM