问题
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