如图效果:
上面是一个textBrowser控件,用来显示我发的东西
下面是一个textedit控件,用来发东西
所以,这里实现的是在textedit里面输入文字,按下enter之后,文字到上面去了,当然也可以单击“发送”
ui界面如图:
代码如下
widget.h中
1 #ifndef WIDGET_H
2 #define WIDGET_H
3
4 #include <QWidget>
5
6 namespace Ui {
7 class Widget;
8 }
9
10 class Widget : public QWidget
11 {
12 Q_OBJECT
13
14 public:
15 explicit Widget(QWidget *parent = 0);
16 ~Widget();
17 protected:
18 bool eventFilter(QObject *target, QEvent *event);//事件过滤器
19
20 private slots:
21 void on_send_clicked();
22
23 private:
24 Ui::Widget *ui;
25 };
26
27 #endif // WIDGET_H
widget.cpp
1 #include "widget.h"
2 #include "ui_widget.h"
3 #include<QKeyEvent>
4 Widget::Widget(QWidget *parent) :
5 QWidget(parent),
6 ui(new Ui::Widget)
7 {
8 ui->setupUi(this);
9 ui->textEdit->setFocusPolicy(Qt::StrongFocus);
10 ui->textBrowser->setFocusPolicy(Qt::NoFocus);
11
12 ui->textEdit->setFocus();
13 ui->textEdit->installEventFilter(this);//设置完后自动调用其eventFilter函数
14
15 }
16
17 Widget::~Widget()
18 {
19 delete ui;
20 }
21 bool Widget::eventFilter(QObject *target, QEvent *event)
22 {
23 if(target == ui->textEdit)
24 {
25 if(event->type() == QEvent::KeyPress)//回车键
26 {
27 QKeyEvent *k = static_cast<QKeyEvent *>(event);
28 if(k->key() == Qt::Key_Return)
29 {
30 on_send_clicked();
31 return true;
32 }
33 }
34 }
35 return QWidget::eventFilter(target,event);
36 }
37
38 void Widget::on_send_clicked()
39 {
40 QString msg = ui->textEdit->toHtml();
41 ui->textEdit->clear();
42 ui->textEdit->setFocus();
43 ui->textBrowser->append(msg);
44
45 }