Windowsでは、すばらしい機能が表示されます。フィールドに完全に収まらない長すぎるテキストを含む短いテキストフィールドにマウスを合わせると、ツールチップが開き、テキストフィールドの完全な内容が表示されます。
誰かがQLineEditでこれを行うコードスニペットを教えてもらえますか?
次のように QLineEdit から派生したカスタム クラスを作成します。
#ifndef LINEEDIT_H
#define LINEEDIT_H
#include <QtGui>
class LineEdit : public QLineEdit
{
Q_OBJECT
public:
LineEdit();
public slots:
void changeTooltip(QString);
};
LineEdit::LineEdit()
{
connect(this, SIGNAL(textChanged(QString)), this, SLOT(changeTooltip(QString)));
}
void LineEdit::changeTooltip(QString tip)
{
QFont font = this->font();
QFontMetrics metrics(font);
int width = this->width();
if(metrics.width(tip) > width)
{
this->setToolTip(tip);
}
else
{
this->setToolTip("");
}
}
#include "moc_LineEdit.cpp"
#endif // LINEEDIT_H
次に、それを何にでも追加します:
#include <QtGui>
#include "LineEdit.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
LineEdit edit;
edit.show();
return app.exec();
}
上記のコメントで述べたように、ここで改善された機能。
void LineEdit::changeTooltip(QString tip)
{
QFont font = this->font();
QFontMetrics metrics(font);
// get the (sum of the) left and right borders;
// note that Qt doesn't have methods
// to access those margin values directly
int lineMinWidth = minimumSizeHint().width();
int charMaxWidth = metrics.maxWidth();
int border = lineMinWidth - charMaxWidth;
int lineWidth = this->width();
int textWidth = metrics.width(tip);
if (textWidth > lineWidth - border)
this->setToolTip(tip);
else
this->setToolTip("");
}
テキストが変更されるたびにツールチップを変更することができます:
まず、QLineEdit からの textChanged() シグナルに反応するプライベート スロットを定義します (QTextEdit が属するクラスのヘッダー ファイル内)。
....
private slots:
void onTextChanged();
....
次に、cpp ファイルで、定義したスロットに QLineEdit textChanged() シグナルを接続し、テキストが変更されたときの動作を実装します。
// In constructor, or wherever you want to start tracking changes in the QLineEdit
connect(myLineEdit, SIGNAL(textChanged()), this, SLOT(onTextChanged()));
最後に、スロットは次のようになります。
void MainWindow::onTextChanged() {
myLineEdit->setTooltip(myLineEdit->text());
}
MainWindow というクラスに QLineEdit が含まれているとします。