我有一个数字1-9和0的拨号盘,上面有一个QLabel,可以显示单击时的数字(与任何电话上的小键盘相同)。全部都是按钮。什么是让QLabel在单击按钮时显示数字的最简单方法?
例如,如果单击2,然后单击0,然后单击7,则标签将实时更新为207。Qlabel的格式应遵循标准电话号码000-000-0000。我知道如何一次将setText设置为一个数字,但它们始终相互覆盖。 任何帮助表示赞赏。 预先谢谢你
答案 0 :(得分:2)
您要寻找的是QSignalMapper
。它通过一个接口映射多个输入,并为您进行发送方分派。
QSignalMapper *mapper(new QSignalMapper(parent));
for (int i=0; i<10; ++i){
QPushButton *button = some_new_button_function();
connect(button, &QPushButton::clicked, mapper, &QSignalMapper::map);
mapper->setMapping(button, i);
}
connect(mapper, QOverload<int>::of(&QSignalMapper::mapped),
[this](int i){/*here your append code*/});
答案 1 :(得分:1)
最简单的方法是将按钮的clicked
信号连接到插槽(可能是lambda),该插槽可更改QLabel
的文本(使用setText()
)。如果要附加到当前文本,则只需执行setText(label.text() + "new text");
。
答案 2 :(得分:0)
您必须将每个clicked()
发出的信号QPushButton
连接到更新QLabel
文本的插槽。
简短示例
在父级构造函数中:
connect(qpb1, &QPushButton::clicked, this, &MyClass::handleQLabel);
以及可能的插槽实现:
void MyClass::handleQLabel()
{
QPushButton * qpb = qobject_cast<QPushButton*>(sender()); // Find the sender of the signal
if(qpb != nullptr)
this->myLabel->setText(qpb->text()); // Write anything you want in the QLabel
else
{
// Do what you want.
}
}
这将完成工作。
当然,如果您不想使用sender()
(例如,对于多线程问题),则可以通过QPushButton
创建一个插槽,并执行相同数量的connect
(繁琐且非常肮脏的解决方法),或者创建QPushButton
的子类以添加自定义信号,以QPushButton
的标识符进行发射,并例如通过插槽获取它。
我希望它可以帮助:)
答案 3 :(得分:0)
QLineEdit可能会更适合您的需求。您可以将其设置为只读,如果愿意,可以禁用交互标志(但是从UI / UX角度来看,最好不要这样做,因为大多数情况下没有理由禁止复制),还可以设置input mask 。鉴于当前的情况,您可以根据以下示例来满足您的需求:
// Set your format.
ui->lineEdit->setInputMask("000-000-0000");
// Make sure that your text would be in the format you like initially.
ui->lineEdit->setText("999-999-9999");
// Text will be not editable.
ui->lineEdit->setReadOnly(true);
// And here, you can use QSignalMapper as other members have suggested. Or you can just connect multiple buttons somehow. The choice is yours to make.
connect(ui->pushButton, &QPushButton::clicked, ui->lineEdit, [this]
{
// Just keep in mind taht when returning text, some of the mask elements might be here, too.
ui->lineEdit->setText(ui->lineEdit->text().replace("-", "") + "1");
});