2012-02-29 122 views
10

我有一个QTextEdit作为“显示器”(可编辑为false)。它显示的文字是字迹包装。现在我希望设置此文本框的高度,以便文本完全适合(同时还要考虑最大高度)。qtextedit - 调整大小以适合

基本上,布局下面的小部件(在同一垂直布局中)应尽可能多地占用空间。

这怎么能最容易实现?

+1

不能在QT库找到qtextbox – 2012-02-29 21:19:16

+0

意味的QTextEdit,固定(带链接) – paul23 2012-02-29 21:24:11

+0

如果你把其他的QTextEdit里面QScrollArea(设置最大高度),你可以使用我给有相同的代码:HTTP://计算器.com/questions/7301785/react-on-the-resizing-a-qmainwindow-for-adjust-widgets-size – alexisdm 2012-03-01 01:40:26

回答

1

当前基础文本的大小可以通过

QTextEdit::document()->size(); 

可我相信,使用此,我们可以相应地调整小部件。

#include <QTextEdit> 
#include <QApplication> 
#include <iostream> 
using namespace std; 

int main(int argc, char *argv[]) 
{ 
    QApplication a(argc, argv); 
    QTextEdit te ("blah blah blah blah blah blah blah blah blah blah blah blah"); 
    te.show(); 
    cout << te.document()->size().height() << endl; 
    cout << te.document()->size().width() << endl; 
    cout << te.size().height() << endl; 
    cout << te.size().width() << endl; 
// and you can resize then how do you like, e.g. : 
    te.resize(te.document()->size().width(), 
       te.document()->size().height() + 10); 
    return a.exec();  
} 
+0

转换为“文档”时不会丢失单词包装吗? – paul23 2012-02-29 22:41:51

+0

尝试编译我放入答案的代码,您会看到小部件的大小和所包含文档的大小之间的差异。 Word包装不会丢失。但是你需要先显示这个小部件。 – 2012-02-29 22:54:27

+0

好吧,这并没有真正解决 - 因为使用'setText()'命令时没有设置大小。 – paul23 2012-03-01 21:54:46

2

除非有一个QTextEdit好需要的能力的东西特别是自动换一个QLabel开启后就会做你想要什么。

+4

只需在单词边界上标记wordwrap,也不会在数据太大时显示滚动条。我开始使用标签,但我需要两个功能集似乎... – paul23 2012-02-29 22:40:19

+1

那么,'QLabel'不会工作:) – 2012-02-29 22:44:16

8

我发现一个非常稳定,简单的解决方案,使用QFontMetrics

from PyQt4 import QtGui 

text = ("The answer is QFontMetrics\n." 
     "\n" 
     "The layout system messes with the width that QTextEdit thinks it\n" 
     "needs to be. Instead, let's ignore the GUI entirely by using\n" 
     "QFontMetrics. This can tell us the size of our text\n" 
     "given a certain font, regardless of the GUI it which that text will be displayed.") 

app = QtGui.QApplication([]) 

textEdit = QtGui.QPlainTextEdit() 
textEdit.setPlainText(text) 
textEdit.setLineWrapMode(True)  # not necessary, but proves the example 

font = textEdit.document().defaultFont() # or another font if you change it 
fontMetrics = QtGui.QFontMetrics(font)  # a QFontMetrics based on our font 
textSize = fontMetrics.size(0, text) 

textWidth = textSize.width() + 30  # constant may need to be tweaked 
textHeight = textSize.height() + 30  # constant may need to be tweaked 

textEdit.setMinimumSize(textWidth, textHeight) # good if you want to insert this into a layout 
textEdit.resize(textWidth, textHeight)   # good if you want this to be standalone 

textEdit.show() 

app.exec_() 

(请原谅我,我知道你的问题是关于C++和我使用Python,但在Qt他们几乎同样的事情反正)。

0

说到Python,我发现.setFixedWidth(your_width_integer).setFixedSize(your_width, your_height)相当有用。不确定C是否具有类似的小部件属性。

0

就我而言,我将QLabel放在QScrollArea中。如果你非常热衷,你可以将两者结合起来并制作你自己的小部件。

相关问题