2013-02-19 206 views
2

的Windows 7 SP1
MSVS 2010
的Qt 4.8.4
如何使用QLineEdit使光標從其內容的開始處開始?

此代碼:

#include <QTGui> 

int main(int argc, char *argv[]) 
{ 
    QApplication app(argc, argv); 
    QMainWindow*   window = new QMainWindow; 
    QLineEdit*   line_edit = new QLineEdit; 

    line_edit->setText("ABCDEFG"); 
    line_edit->setFixedSize(40,20); 
    window->setCentralWidget(line_edit); 
    window->show(); 
    return app.exec(); 
} 

顯示此:

enter image description here

注意, 「AB」 被截斷並且光標位於行編輯的末尾。

我希望它顯示:

enter image description here

這裏的「FG」是截斷,並且光標在行編輯的開始。

我試圖設置光標位置和cursorBackward無濟於事。如果我通過字體指標的elidedText轉換文本,它將從尾部的「...」開始顯示。但我不想這樣做。

問:有沒有辦法讓光標在顯示QLineEdit後在其內容的開始處開始?

回答

1

設置光標位置爲0剛過設置文本應該只是罰款。至少它在Linux上是這樣的,Qt 4.8.3。

#include <QtGui> 

int main(int argc, char *argv[]) 
{ 
    QApplication app(argc, argv); 
    QMainWindow*   window = new QMainWindow; 
    QVBoxLayout*   layout = new QVBoxLayout; 
    QLineEdit*   line_edit = new QLineEdit; 

    line_edit->setText("ABCDEFG"); 
    line_edit->setFixedSize(40,20); 
    line_edit->setCursorPosition(0); 
    layout->addWidget(line_edit); 
    window->setCentralWidget(line_edit); 
    window->show(); 
    return app.exec(); 
} 
+0

這工作完美。我在我的大型程序中發現了我的問題:在設置文本之前,我正在設置光標位置。設置文本後設置它解決了我的問題。再一次感謝你的幫助! – 2013-02-19 23:15:56

1

setCursorPosition(0)爲我工作得很好:

// ... 
line_edit->setFixedSize(40,20); 
line_edit->setCursorPosition(0); 
// ... 

(在Windows,VC++ 2010,Qt5.0.0)

+0

@Jakob Leben你是對的。我道歉。我在setCursorPostion無法工作的更大的程序中遇到此問題。我將問題簡化爲一個簡單的插圖程序,但忽略了在那裏測試setCursorPostion。我需要進一步分析爲什麼這不適用於我的大型項目。謝謝! – 2013-02-19 23:05:48

+0

@Macbeth:不用擔心,祝你好運發現錯誤! – Cameron 2013-02-19 23:21:14

+0

我在我的大型程序中發現了我的問題:在設置文本之前,我正在設置光標位置。設置文本後設置它解決了我的問題。再一次感謝你的幫助! – 2013-02-20 00:24:28