上一个考试问题:使用单个插槽中的按钮从其文本中提取按钮的按键。编写一个名为keyPressed()的插槽函数。
我很难弄清楚如何使用SLOT函数keyPressed()中的信号(键1,键2等)。例如。因此,在SLOT功能中按下了key1,使用了“ 1”,按下了key2,使用了“ 2”,等等。
编辑:这里是一个解决方案,可帮助我的班级同学。
使用QGROUPBUTTON。
passwordQt.h
#ifndef PASSWORDQT_H
#define PASSWORDQT_H
#include <QDialog>
#include <QLabel>
#include <QButtonGroup>
class passwordQt: public QDialog
{
Q_OBJECT
private:
QString password;
QLabel * passwordLabel;
QButtonGroup* buttonGroup; //new private member variable
public:
passwordQt();
public slots:
void keyPressed(int index);
};
#endif // PASSWORDQT_H
passwordQt.cpp
passwordQt::passwordQt() : password(""), passwordLabel(new QLabel(""))
{
QPushButton * key1 = new QPushButton("1");
QPushButton * key2 = new QPushButton("2");
QPushButton * key3 = new QPushButton("3");
QPushButton * key4 = new QPushButton("4");
QPushButton * OKButton = new QPushButton("OK");
QVBoxLayout * vLayout = new QVBoxLayout();
QHBoxLayout * keysLayout = new QHBoxLayout();
vLayout->addWidget(passwordLabel);
keysLayout->addWidget(key1);
keysLayout->addWidget(key2);
keysLayout->addWidget(key3);
keysLayout->addWidget(key4);
vLayout->addLayout(keysLayout);
vLayout->addWidget(OKButton);
setLayout(vLayout);
buttonGroup = new QButtonGroup();
buttonGroup->addButton((key1));
buttonGroup->addButton((key2));
buttonGroup->addButton((key3));
buttonGroup->addButton((key4));
//all keys stored in buttonGroup object
connect(buttonGroup, SIGNAL(buttonClicked(int)), this, SLOT(keyPressed(int)));
//buttonClicked(int) as opposed to "clicked()"
connect(OKButton, SIGNAL(clicked()), this, SLOT(close()));
}
void passwordQt::keyPressed(int index)
{
password += buttonGroup->button(index)->text();
//this part blew me away. Would never have found this
passwordLabel->setText(QString(password.length(), '*'));
}
最终结果是,密码存储在QString密码中,但显示为星号。如果按下按钮1,则将存储1并显示1星。如果接下来按下按钮3,则3将存储在1旁边,现在总共显示两颗星。