简体   繁体   中英

Qt Type as parameter of function

I am trying to build a function that takes a (qt) Type as a parameter and uses it to find children. My function looks like this:

template <typename QType>
void MyClass::activateElements(QWidget *widget, QType t)
{
    QList<QType *> buttons = widget->findChildren(t);
    foreach( QType *button, buttons )
    {
        buttons->setEnabled(true);
    }
}

I have also tried

template <typename QType>
void MyClass::activateElements(QWidget *widget, QType)
{
    QList<QType *> buttons = (* widget).findChildren<QType *>();
    foreach( QType *button, buttons )
    {
        button->setEnabled(true);
    }
}

I instantiate an object of the class that uses this function in another class. There I try to use it like this:

    QDoubleSpinBox x;
    object_of_my_class->activateElements(correctWidget, x);

At this point I get stuck because I get the following error:

error: 'QDoubleSpinBox::QDoubleSpinBox(const QDoubleSpinBox&)' is private Q_DISABLE_COPY(QDoubleSpinBox)

How would I handle this problem, that QDoubleSpinBox and others are private? Have I approached how to build the function wrong or am I just using it incorrectly? Is there even a way to do it?

It looks like you don't need an object of the type at all, only the type itself. In such case, specifying the template argument would be the way to go:

template <typename QType>
void MyClass::activateElements(QWidget *widget)
{
    QList<QType *> buttons = (* widget).findChildren<QType *>();
    foreach( QType *button, buttons )
    {
        button->setEnabled(true);
    }
}

// Usage:
object_of_my_class->activateElements<QDoubleSpinBox>(correctWidget);

This is how I would do it, as it expresses intent quite well.

If, however, you really want to enable type deduction from an existing object, pass it by reference to avoid the (forbidden) copy:

template <typename QType>
void MyClass::activateElements(QWidget *widget, const QType &)
{
    QList<QType *> buttons = (* widget).findChildren<QType *>();
    foreach( QType *button, buttons )
    {
        button->setEnabled(true);
    }
}

// Usage:
QDoubleSpinBox x;
object_of_my_class->activateElements(correctWidget, x);

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