How to use templates with QT signals and slots?

こ雲淡風輕ζ 提交于 2019-12-12 07:57:42

问题


I want to use signals and slots in my program, but unfortunately they should be used for transmitting several different data types (e.g. QString, double, etc.) and I don't want to write twenty different slots just because I need one for each data type. But when I want to declare a slot like

template <typename t>
void Slot1(t data);

QT tells me that it is not possible to use templates in signals and slots. Is there a workaround? Or can my approach simply improved?


回答1:


Accurate answer: It is impossible

Workaround: You can do something like this with new signals and slots syntax:

QSlider *slid = new QSlider;
QLineEdit *lne = new QLineEdit;

connect(slid,&QSlider::valueChanged,this,&MainWindow::random);
connect(lne,&QLineEdit::textChanged,this,&MainWindow::random);
lne->show();
slid->show();

Slot:

void MainWindow::random(QVariant var)
{
    qDebug() << var;
}

Output:

QVariant(int, 11) 
QVariant(int, 12) 
QVariant(int, 13) 
QVariant(int, 14) 
QVariant(int, 16) 
QVariant(QString, "c") 
QVariant(QString, "cv") 
QVariant(QString, "cvb") 
QVariant(QString, "cvbc") 
QVariant(QString, "cvbcv")

Why? http://qt-project.org/wiki/New_Signal_Slot_Syntax

Possibility to automatically cast the types if there is implicit conversion (e.g. from QString to QVariant)



来源:https://stackoverflow.com/questions/26950718/how-to-use-templates-with-qt-signals-and-slots

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!