2016-04-25 121 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上進行過測試,我還沒有做過像素級比較。

編輯:我看到對齊失敗,不同的字體大小。