View Full Version : QLabel selection: start and end position?

11th January 2009, 20:07
I have no idea if this is possible, but i need to figure out how to get the start and end position of the selected text in a QLabel. I have multiple QLabels that can have their text selected, so i also need to know how to pick up which one has text selected. I use QLabels because it's the only widget i know that doesn't supply its own scrollbars when there is a lot of content; i need the widget to stretch out as much as the content needs. However, if the same can be done with other widgets (i.e. stretch out according to content), then i'm all ears. I can pretty much figure out how to obtain the selected text in a QLabel, but not the start and end positions.

16th January 2009, 18:58
Interesting problem. The only way I found was to rely on a private header:

#include <QtGui>
#include <private/qtextcontrol_p.h>

class Label : public QLabel
Label(QWidget* parent = 0) : QLabel(parent)
setText("Qt Centre");
setTextFormat(Qt::RichText); // <-- mandatory to force QTextDocument to be created
setTextInteractionFlags(Qt::TextSelectableByMouse) ;

QTextControl* control = findChild<QTextControl*>();
connect(control, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));

private slots:
void onSelectionChanged()
QTextControl* control = findChild<QTextControl*>();
QTextCursor cursor = control->textCursor();
qDebug() << cursor.selectionStart() << cursor.selectionEnd() << cursor.selectedText();

int main(int argc, char* argv[])
QApplication app(argc, argv);
Label label;
label.setText("Qt Centre");
return app.exec();

#include "main.moc"

18th January 2009, 02:00
Didn't realize QTextControl existed. Thanks for the help.