C++ QT文本编辑/文本浏览器动态高度
我对QT非常陌生,我创建了一个GUI应用程序,其中包含以下代码: main window.hC++ QT文本编辑/文本浏览器动态高度,c++,qt,qt-creator,qtextedit,C++,Qt,Qt Creator,Qtextedit,我对QT非常陌生,我创建了一个GUI应用程序,其中包含以下代码: main window.h #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget
#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
使用设计器,我在表单布局中进行了文本编辑。当文本编辑中有太多内容时,它会生成一个滚动条,而不是根据内容调整大小
我疯狂地在谷歌上搜索,但我找到的所有答案都远远超出了我的水平,所以我根本不懂。我非常想实现这一点,因为它是我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);
}
您希望大小如何适应内容?是否要调整整个窗口的大小?
QTextEdit
acentralWidget
是main窗口的?您不应该使用designer,只需在最小的测试用例中以编程方式创建ui。将所有内容放在一个文件中,无需将其拆分-记住,这是一个测试用例,而不是一个软件项目。
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);