QT文本编辑/文本浏览器动态高度

时间:2013-10-13 21:53:12

标签: c++ qt qt-creator qtextedit

我是QT的新手,我创建了一个GUI应用程序,其中包含以下代码:

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

的main.cpp

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

使用设计器我在表单布局中创建了一个textEdit。当我在textEdit中有太多内容时,它会创建一个滚动条而不是调整内容的大小。

我用疯子搜索了,但我发现的所有答案都超出了我的水平,所以我根本就不理解它们。我想要实现这一点非常糟糕,因为这是我的gui的核心。

提前致谢

1 个答案:

答案 0 :(得分:0)

没有标准的方法可以做到这一点。这是我的解决方法:

部首:

class Text_edit_auto_height : public QObject {
  Q_OBJECT
public:
  explicit Text_edit_auto_height(QTextEdit* edit);

private:
  QTextEdit* _edit;
  bool eventFilter(QObject* object, QEvent* event);

  QTimer timer;

private slots:
  void update_height();

};

来源:

#include "Text_edit_auto_height.h"
#include <QEvent>

Text_edit_auto_height::Text_edit_auto_height(QTextEdit* edit) :
  QObject(edit)
, _edit(edit)
{
  connect(edit->document(), SIGNAL(contentsChanged()), this, SLOT(update_height()));
  update_height();
  edit->installEventFilter(this);
  connect(&timer, SIGNAL(timeout()), this, SLOT(update_height()));
  timer.start(500);
}

bool Text_edit_auto_height::eventFilter(QObject *object, QEvent *event) {
  if (event->type() == QEvent::Resize) {
    update_height();
  }
  return false;
}

void Text_edit_auto_height::update_height() {
  _edit->setFixedHeight(_edit->document()->size().height() + 5);
}

用法:将它放在构造函数中:

new Text_edit_auto_height(ui->list);
相关问题