如何使用模板与QT信号和插槽? [英] How to use templates with QT signals and slots?
问题描述
我想在我的程序中使用信号和插槽,但不幸的是,它们应该用于传输几种不同的数据类型(例如QString,double等),我不想写20个不同的插槽,只是因为我需要每个数据类型一个。但是当我要声明一个像
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告诉我,不可能在信号和插槽中使用模板。有解决方法吗?
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?
推荐答案
您可以使用新的信号和插槽语法:
You can do 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();
插槽:
void MainWindow::random(QVariant var)
{
qDebug() << var;
}
输出:
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")
http://qt-project.org/wiki/New_Signal_Slot_Syntax
如果存在隐式
转换(例如从QString到QVariant),可以自动转换类型
Possibility to automatically cast the types if there is implicit conversion (e.g. from QString to QVariant)
这篇关于如何使用模板与QT信号和插槽?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!