[英]How to send key to parent mainWindow from dialog in QT C++
我需要一個用於嵌入式 linux 應用程序(不是 QML)的虛擬鍵盤。 我找不到更好的方法,所以現在我正在嘗試創建一個。 我想要一個充滿按鈕的對話框,將鍵發送到父mainWindow
。 它運行時沒有錯誤,但在lineEdit
什么也沒發生。
Keyboard::Keyboard(QWidget *parent) :
QDialog(parent),
ui(new Ui::Keyboard)
{
ui->setupUi(this);
mainWindow = this->parent();
}
void Keyboard::on_btnA_clicked()
{
qDebug() << "Test1";
QKeyEvent event(QEvent::KeyPress, Qt::Key_A, Qt::NoModifier);
qDebug() << "Test2";
QApplication::sendEvent(mainWindow, &event);
qDebug() << "Test3";
}
在 mainWindow.cpp 中打開鍵盤對話框:
keyboard->show();
ui->lineEdit->setFocus();
問題是什么? 提前致謝。
幾件事:
將事件發送到mainWindow
需要mainWindow
處理將事件傳遞給QLineEdit
對象,而沒有看到其余的代碼我不能說這是否正在完成; 另一種方法是直接發送到QLineEdit
如下所示:
QApplication::sendEvent(lineEdit, &event);
QKeyEvent
構造函數還需要第四個參數 - 要發送的字符串,在示例中為"a"
。
QKeyEvent event(QEvent::KeyPress, Qt::Key_A, Qt::NoModifier);
應該
QKeyEvent event(QEvent::KeyPress, Qt::Key_A, Qt::NoModifier, "a");
發送一個"a"
。
根據具體的實現,您可能還需要在QEvent::KeyPress
之后發送QEvent::KeyRelease
,即
QKeyEvent event1(QEvent::KeyPress, Qt::Key_A, Qt::NoModifier, "b"); QKeyEvent event2(QEvent::KeyRelease, Qt::Key_A, Qt::NoModifier); QApplication::sendEvent(edit, &event1); QApplication::sendEvent(edit, &event2);
如 (2) 所示,鍵枚舉(即Qt::Key_A
)不會像您期望的那樣發送"a"
,發送的字符串由QKeyEvent
構造函數中的第四個參數決定,即
QKeyEvent event(QEvent::KeyPress, Qt::Key_A, Qt::NoModifier, "a"); QApplication::sendEvent(lineEdit, &event);
相當於
QKeyEvent event(QEvent::KeyPress, Qt::Key_B, Qt::NoModifier, "a"); QApplication::sendEvent(lineEdit, &event);
以這種方式使用QKeyEvent
可能會導致處理退格和刪除時出現一些不愉快。 簡單地將所需字符附加到QLineEdit
文本可能更優雅,
lineEdit->setText(lineEdit->text().append("a"));
並使用QLineEdit::backspace()
和QLineEdit::delete()
處理backspace
和delete
鍵。
#include <QtWidgets/QApplication>
#include <qwidget.h>
#include <qmainwindow.h>
#include <qlineedit.h>
#include <qboxlayout.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QMainWindow* main = new QMainWindow;
QWidget* central = new QWidget();
QBoxLayout* layout = new QBoxLayout(QBoxLayout::LeftToRight);
central->setLayout(layout);
QLineEdit* edit = new QLineEdit(central);
edit->setAlignment(Qt::AlignCenter);
layout->addWidget(edit);
edit->setText("sometext");
edit->backspace();
edit->setText(edit->text().append("a"));
main->setCentralWidget(central);
main->resize(600, 400);
main->show();
return a.exec();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.