[英]QT Text Edit/Text Browser dynamic height
我對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的核心。
提前致謝
沒有標准方法可以做到這一點。 這是我的解決方法:
標題:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.