Qt C++如何在类中使用 keyPressEvent 进行 QWidget
Qt C++ how to use keyPressEvent for a QWidget within a class
我正在尝试使用keyPressEvent,但它仅在窗口具有焦点而不是任何QWidgets时才起作用。
这是我的代码:
在customdialog.h中:
class CustomDialog : public QDialog, public Ui::CustomDialog
{
Q_OBJECT
private:
Ui::CustomDialog *ui;
QString lastKey;
public:
CustomDialog(QWidget * parent = 0);
protected:
void keyPressEvent(QKeyEvent *e);
};
在自定义对话框中.cpp:
void CustomDialog::keyPressEvent(QKeyEvent *e)
{
lastKey = e->text();
qDebug() << lastKey;
}
如何使此类中的所有小部件使用相同的键按事件?
您可以通过将事件过滤器安装到自定义对话框的每个子级来解决您的问题:
void CustomDialog::childEvent(QChildEvent *event)
{
if (event->added()) {
event->child()->installEventFilter(this);
}
}
bool CustomDialog::eventFilter(QObject *, QEvent *event)
{
if (event->type() == QEvent::KeyPress)
keyPressEvent(static_cast<QKeyEvent*>(event));
return false;
}
但是,由于每个被忽略的 keyPress 事件都会发送到父小部件,因此您可以为同一事件多次调用 keyPressEvent。
我最终决定在这种情况下不使用keyPressEvent来实现我的目的。我只需要在QTextBrowser中按下最后一个键。这是我最终做的事情:
connect(ui->textBrowser, SIGNAL(textChanged()), this, SLOT(handleTextBrowser()));
void CustomDialog::handleTextBrowser()
{
QTextCursor cursor(ui->textBrowser->textCursor());
QString key = ui->textBrowser->toPlainText().mid(cursor.position() - 1, 1);
qDebug() << key;
}
相关文章:
- 通过递归进行因子分解
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 我可以使用 g++ 进行三种比较 (<=>) 吗?
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- 使用libgit2、c++进行pull
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 如何使用模板函数的函数签名进行SFINAE
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 将模板化的类型与C++中的某些类/类型进行比较
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 如何对点云数据进行排序
- 从文本文件中读取时钟时间和事件时间并进行处理
- 对字符串进行位操作
- 是否可以使用winusb同时与多个相同的usb设备进行通信
- 是否可以对零模板参数进行模板专门化
- 对字符串进行排序时,在c++中处理sort()
- 试图对缓存进行跨步测试,但程序并没有结束
- 有什么好的方法可以让系统调用代理允许在单元测试中进行模拟
- Qt C++如何在类中使用 keyPressEvent 进行 QWidget