Using QTimeEdit with time_t - Adapter pattern C++

174 Views Asked by At

I need to make an adapter for QTimeEdit to use it with time_t in:

  1. constructor QTimeEdit(time_t)
  2. void setTime(time_t)
  3. time_t time() I did 1. and its working.
class QTimeEditAdapter: public QTimeEdit {
public:
    QTimeEditAdapter(time_t t) {
        tm1 = t;
        tm *ltm = localtime(&tm1);
        int hours = ltm->tm_hour;
        int min = ltm->tm_min;
        this->setTime(QTime(hours,min));
    }
private:
    time_t tm1;
};
int main(int argc, char *argv[])
{
    time_t tm1;
    tm1 = time(NULL);

    //other qt widgets code

    QTimeEdit* timeEdit = new QTimeEditAdapter(tm1);

    //more other qt widgets code

But if I'm adapting setTime by adding

void setTime(time_t t1)

to the class its redefines setTime and I'm getting mistakes from both constructor and method setTime. I didn't found any other method to set time in QTimeEdit but I guess there must be a way better than my

1

There are 1 best solutions below

0
On BEST ANSWER

A derived-class member with the same name as a member of the base class hides direct use off the base-class member -- C++ Primer (5th Edition), Pg 618

Function overloading based on the parameter list is not possible between derived and base classes. If you make a call like this->setTime(QTime(hours,min)); where this is a QTimeEditAdapter, only your new QTimeEditAdapter::setTime(time_t) will be considered in the overload resolution. This causes the compile error.

To workaround this, you could directly reference the base-class in the constructor:

QTimeEditAdapter::setTime(QTime(hours,min));

but this won't help other users of your adaptor access the original setTime.

Another workaround would be to instead add the following:

void setTime(QTime qt)
{
        QTimeEdit::setTime(qt);
}

This fixes the issue, but now you are responsible for enumerating all (present or future) possible overloads that the base class defines.

To avoid these tricky issues it's probably better to just pick a different method name for your QTimeEditAdapter::setTime(time_t) method.