如何使QTextBrowser在QVBoxLayout中很好地扩展?

时间:2011-04-08 09:05:40

标签: qt

我想在可滚动列表中显示一个简短的html片段列表。因此,我将QVboxLayout放入QScrollArea并添加多个QTextBrowsers:

#include <QApplication>
#include <QScrollArea>
#include <QTextBrowser>
#include <QVBoxLayout>

int main(int argc, char *argv[]) {
  QApplication app(argc, argv);

  QScrollArea scrollArea;
  scrollArea.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  scrollArea.setWidgetResizable(true);
  QWidget *scrollWidget = new QWidget;
  QVBoxLayout *layout = new QVBoxLayout;

  for(int i=0;i<6;i++) {
    QString text = "some <b>text</b> ";
    for(int j=0;j<i;j++) text += text;

    QTextBrowser *browser = new QTextBrowser();
    QTextDocument *doc = new QTextDocument(browser);
    doc->setHtml(text);
    browser->setDocument(doc);

    layout->addWidget(browser);
  }

  scrollWidget->setLayout(layout);
  scrollArea.setWidget(scrollWidget);

  scrollArea.show();
  return app.exec();
}

我的问题:这些盒子都有相同的尺寸。我希望它们尽可能大,但不要大。我怎么能让文字浏览器占用他们真正需要的空间呢?

2 个答案:

答案 0 :(得分:0)

好的,我找到了一个源自http://www.qtcentre.org/threads/39839-QTextBrowser-height-adjusted-to-content的解决方案。是否有更简单/更优雅的解决方案?

#include <QApplication>
#include <QScrollArea>
#include <QTextBrowser>
#include <QVBoxLayout>
#include <QGroupBox>
#include <QDebug>

#include <QShowEvent>
#include <QResizeEvent>

class MyBrowser : public QTextBrowser {
private:
  QTextDocument *doc;

public:
  MyBrowser(const QString &text, QWidget *parent = 0) : QTextBrowser(parent) {
    doc = new QTextDocument(this);
    doc->setHtml(text);
    setDocument(doc);
  }

  void adjust() {
    QMargins margins = contentsMargins();

    int width = size().width() - 
      margins.left() - margins.right() - doc->documentMargin()*2;
    doc->setPageSize(QSizeF(width,-1));

    int height = doc->size().height() + margins.top() + margins.bottom();
    setMaximumHeight(height);
    setMinimumHeight(height);
  }

  void showEvent(QShowEvent *) {
    adjust();
  }

  void resizeEvent(QResizeEvent *) {
    adjust();
  }
};

int main(int argc, char *argv[]) {
  QApplication app(argc, argv);

  QScrollArea scrollArea;
  scrollArea.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  scrollArea.setWidgetResizable(true);
  QWidget *scrollWidget = new QWidget;
  QVBoxLayout *layout = new QVBoxLayout;

  for(int i=0;i<6;i++) {
    QString text = "some <b>text</b> ";
    for(int j=0;j<i;j++) text += text;

    MyBrowser *browser = new MyBrowser(text, scrollWidget);
    layout->addWidget(browser, 0, 0);
  } 

  scrollWidget->setLayout(layout);
  scrollArea.setWidget(scrollWidget);

  scrollArea.show();
  return app.exec();
}

答案 1 :(得分:-1)

而不是做

layout->addWidget(browser);

你应该这样做:

layout->addWidget(browser, 0, 0);

这将告诉QT不要根据其布局来拉伸小部件。