PDA

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



truefusion
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.

jpn
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
{
Q_OBJECT
public:
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*>();
Q_ASSERT(control);
connect(control, SIGNAL(selectionChanged()), this, SLOT(onSelectionChanged()));
}

private slots:
void onSelectionChanged()
{
QTextControl* control = findChild<QTextControl*>();
Q_ASSERT(control);
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");
label.show();
return app.exec();
}

#include "main.moc"

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