PDA

View Full Version : How to select a line of text



benlyboy
25th April 2010, 15:47
Hi all

I'm working on my first app using pyqt and i need some help

I want to be able to click on a line of text in a QtextEdit box, and be able to load that line into a string.

How would i do this...?

Thanks :)

Lykurg
25th April 2010, 15:59
Hi,

if you click on a line in a text edit, then also the cursor jumps to that line. Get that cursor via QTextEdit::textCursor() and use QTextCursor::movePosition() with QTextCursor::StartOfBlock and QTextCursor::EndOfBlock to select the line. Then grab the text via QTextCursor::selectedText().

That's all!

benlyboy
25th April 2010, 19:10
Thanks for the reply

maybe you could help out with a demo code.

I've had a play, but no luck. I had thought that to move to a function after a click would be the first step, I was thinking something like this but it didn't work.


self.connect(self.QTextEdit,SIGNAL("clicked()"),self.test)
what am i doing wrong?

qratman
25th April 2010, 20:15
Hi, I am very beginner myself but I tested out what Lykurg said and it works.



I created QTextEdit and QLabel with QTCreator UI editor (based on QDialog).

Added this to dialog class in header


private slots:
void on_textEdit_clicked();


Then I added this into constructor in dialog.cpp.


connect(ui->textEdit, SIGNAL(cursorPositionChanged()), this, SLOT(on_textEdit_clicked()));


and into dialog.cpp:


void Dialog::on_textEdit_clicked()
{
QTextCursor cursor;
QString text;

cursor = ui->textEdit->textCursor();
cursor.movePosition(QTextCursor::StartOfBlock);
cursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
text = cursor.selectedText();

ui->label->setText(text);

}


Sorry, I dont use python. So you've got to translate it yourself.

Works great. I however expected the line to turn blue to indicate selection but this did not happen.

benlyboy
25th April 2010, 20:42
yes thanks that works great:)

thanks all for the help

Lykurg
25th April 2010, 20:59
Works great. Of course, because I said it:cool:

I however expected the line to turn blue to indicate selection but this did not happen.
That is because textCursor() gives a copy of the original (="displayed") text cursor. All things you do with it don't show up in the editor. If you wish so, you have to set it back via setTextCursor(). But be aware that this will in your case end up in a never ending loop because of your connect statement.

In the example, I wouldn't use the clicked() signal. Only use cursorPositionChanged() and check if the line was changed (with a local member variable). Only if it changed, do all the cursor stuff.

wysota
25th April 2010, 23:56
Of course, because I said it:cool:
Lol... I have nothing more to say :rolleyes: