表格上有2个lineEdit'a。数字键盘形式上有一堆按钮(我正在制作一个适用于触摸屏的桌面应用程序)。有必要从这个数字键盘输入数据到lineEdit有焦点的那个。
你怎么解释lineEdito'в现在焦点所在的 QPushButton 呢?
升级版:
按照@magrif 的建议,我做了以下事情:
主窗口.h
bool eventFilter(QObject *watched, QEvent *event);
QObject * m_focused;
void digiKey(QLineEdit *l);
主窗口.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
m_focused = nullptr;
/*...*/
ui->lineEdit_oPrice->installEventFilter(this);
ui->lineEdit_oAmount->installEventFilter(this);
connect(ui->pushButton_0, &QPushButton::clicked, [this]() {
if(m_focused != nullptr) {
QLineEdit* l = static_cast<QLineEdit*>(m_focused);
//do something
digiKey(l);
}
});
}
void MainWindow::digiKey(QLineEdit * l)
{
QPushButton *button = (QPushButton *)sender();
double Price;
qDebug() << "isPrice now";
Price = (l->text() + button->text()).toDouble();
l->setText(QString::number(Price));
}
最终,当点击相关按钮时,程序崩溃。
像这样的东西
通过事件
在
MainWindow(或任何用于 lineedit 聚合的类)中声明一个成员QObject* m_focused;。像这样重新定义虚拟成员函数eventFilter(QObject *watched, QEvent *event):在构造函数中,仅在 lineEdits 上设置此过滤器,并将
m_focused其定义为nullptr:现在,当收到焦点时,指向当前 lineEdit 的指针存储在
m_focused. 然后按类型使用此对象: