2016-04-25 97 views
4

右边的文本我有一个QLabel刚刚与相同尺寸和取向性的QLineEdit如下:对齐从QLabel和QLineEdit的

QLineEdit *lineEdit = new QLineEdit("999"); 
lineEdit->setFixedWidth(100); 
lineEdit->setAlignment(Qt::AlignRight); 
// 
QLabel *label = new QLabel("999"); 
label->setFixedWidth(100); 
label->setAlignment(Qt::AlignRight); 
// 
QLayout *layout = new QVBoxLayout; 
layout->addWidget(lineEdit); 
layout->addWidget(label); 

下面是该如何呈现:

enter image description here

如何将底部label的文本与lineEdit的文本完全对齐?

全额奖励,如果你发现在所有平台上工作的解决方案,而且也适用时的字体大小都在lineEditlabel不同

+0

正如你所看到的,'QLineEdit'使用从边界到文本的分隔符空间(非常类似于'QLayout'的边距。你可以在'label'周围添加一个布局来模拟这种行为 – Zaiborg

+2

有一个看 http://doc.qt.io/qt-4.8/qlabel.html#indent-prop – Ankur

+1

如果你需要计算一个精确的填充,你可以检查[QLineEdit :: textMargins()](http:// doc .qt.io/qt-5/qlineedit.html#textMargins)加上考虑边框宽度。 – ymoreau

回答

6

不幸的是,它可能是不可能的,至少不是开箱即可,右边距不起作用,因为即使文本明显向左偏移,它也始终为0。原因是这个偏移量不是由边距决定的,而是取决于平台GUI风格和正在使用的特定字体的度量的组合,并且其值“方便”在类public interface中不可用,所以没有办法去解决它。

您可以很容易地获得字体指标,但您无法获得QStyleOptionFrame,因为所需的方法受到保护,访问它需要子类QLineEdit。但是,如果你是幸运的,这个值很可能是零,所以你可以用这样简单的东西去:

QVBoxLayout *layout = new QVBoxLayout; 
    QLineEdit *lineEdit = new QLineEdit("999"); 
    lineEdit->setAlignment(Qt::AlignRight); 
    QLabel *label = new QLabel("999"); 
    label->setAlignment(Qt::AlignRight); 

    int offsetValue = lineEdit->fontMetrics().averageCharWidth(); 
    label->setIndent(offsetValue); 

    setLayout(layout); 
    layout->addWidget(lineEdit); 
    layout->addWidget(label); 

如果不为你正常工作,你将没有其他选择但是要继承QLineEdit,请仔细检查它的绘画事件,确定正在计算偏移量的位置,并将该值存储在公共成员中,以便可以从外部访问该值以用于偏移标签。

我个人很幸运与代码:

enter image description here

+0

这是相当简单的代码!因为当QTextEdit字体大于QLabel时,它不起作用,所以我没有回答这个问题。 – mimo

4

你能代替使用QLineEditQLabel使用两个QLineEdits的?

考虑以下几点:

QWidget* widget = new QWidget(); 
// Original line edit 
QLineEdit *lineEdit1 = new QLineEdit("999"); 
lineEdit1->setFixedWidth(100); 
lineEdit1->setAlignment(Qt::AlignRight); 
lineEdit1->setStyleSheet("border-width: 2px;"); 
// A suggestion if you want a label 
QLabel *label = new QLabel("999"); 
label->setFixedWidth(100); 
label->setAlignment(Qt::AlignRight); 
label->setStyleSheet("border: 2px solid rgba(255, 0, 0, 0%)"); 
// Alternatively if you can use another QLineEdit 
QLineEdit *lineEdit2 = new QLineEdit("999"); 
lineEdit2->setFixedWidth(100); 
lineEdit2->setAlignment(Qt::AlignRight); 
lineEdit2->setReadOnly(true); 
lineEdit2->setStyleSheet("background: rgba(0, 0, 0, 0%); " 
         "border-width: 2px;    " 
         "border-style: solid;   " 
         "border-color: rgba(0, 0, 0, 0%);"); 
// Bring it all together 
QLayout *layout = new QVBoxLayout(widget); 
layout->addWidget(lineEdit1); 
layout->addWidget(label); 
layout->addWidget(lineEdit2); 
widget->show(); 

它迫使所有边框是2px的,所以在不同的平台应该是相同的。第二QLineEdit不应该看不同的比QLabel(文字颜色看起来比标签稍深,虽然,这可能是一件好事,因为它原来的编辑匹配)

使用QLineEdit,而不是额外的好处QLabel是价值现在可以选择...

免责声明:我只在Linux上进行过测试,我还没有做过像素级比较。

编辑:我看到对齐失败,不同的字体大小。