×
Namespaces

Variants
Actions

使用 QSignalMapper

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata

测试基于
设备:: Nokia 5800 XpressMusic

兼容于
文章
关键词: QSignalMapper
翻译:
dougcn
最后由 hamishwillee 在 11 Oct 2012 编辑

描述

QSignalMapper 类用于这样的情况:多个信号(signal)连接到同一个槽(slot),而这个槽又需区别处理每个信号。QSignalMapper}'类收纳了一个无参数的信号集,然后相应于原发射信号的对象用整型、字符串或widget参数进行信号重发。QSignalMapper::setMapping()方法用于映射所有widget的信号到单个QSignalMapper对象。而删除映射可以用QSignalMapper::removeMappings()方法。然后widget的信号连接到QSignalMapper::map()槽。最后,QSignalMapper::mapped()信号连接到任何自定义widget的signal/slot做需要的处理。

做法

以转发整型参数为例。

SignalMapper.h

 class SignalMapper : public QMainWindow
{
Q_OBJECT
public:
SignalMapper(QWidget *parent = 0);
~SignalMapper();
public slots:
void digitClicked(int);
private:
Ui::SignalMapperClass ui;
// 3个按钮将在被点击时提供3三个信号
QPushButton *buttons[3];
// 用于显示从哪个按钮来的信号
QLabel* mainlabel;
};

SignalMapper.cpp

 SignalMapper::SignalMapper(QWidget *parent)
: QMainWindow(parent)
{
QWidget* mainwindow = new QWidget(this);
QVBoxLayout* mainlayout = new QVBoxLayout(mainwindow);
// 创建标签和信号映射器
mainlabel = new QLabel(mainwindow);
QSignalMapper *signalMapper = new QSignalMapper(this);
// 连接信号映射器的mapped信号到自定义widget槽
connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(digitClicked(int)));
 
for (int indx = 0; indx < 3; ++indx)
{
QString text = QString::number(indx);
 
// 创建按钮并使能映射
buttons[indx] = new QPushButton(text, mainwindow);
signalMapper->setMapping(buttons[indx], indx);
 
// 连接下压按钮的clicked()信号到到信号映射器的map()槽
connect(buttons[indx], SIGNAL(clicked()), signalMapper, SLOT(map()));
mainlayout->addWidget(buttons[i]);
}
mainlayout->addWidget(mainlabel);
mainwindow->setLayout(mainlayout);
setCentralWidget(mainwindow);
}

函数void digitClicked(int)中根据该函数的参数(按钮数组的索引)具体判断点击了哪个按钮。

This page was last modified on 11 October 2012, at 01:18.
159 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×