summaryrefslogtreecommitdiffstats
path: root/src/widgets
diff options
context:
space:
mode:
Diffstat (limited to 'src/widgets')
-rw-r--r--src/widgets/dialogs/qcolordialog.cpp240
-rw-r--r--src/widgets/dialogs/qcolordialog.h4
-rw-r--r--src/widgets/dialogs/qcolordialog_p.h8
-rw-r--r--src/widgets/dialogs/qdialog.cpp4
-rw-r--r--src/widgets/dialogs/qdialog_p.h2
-rw-r--r--src/widgets/dialogs/qfiledialog.cpp417
-rw-r--r--src/widgets/dialogs/qfiledialog.h64
-rw-r--r--src/widgets/dialogs/qfiledialog_p.h40
-rw-r--r--src/widgets/dialogs/qfileinfogatherer.cpp2
-rw-r--r--src/widgets/dialogs/qfileinfogatherer_p.h8
-rw-r--r--src/widgets/dialogs/qfilesystemmodel.cpp2
-rw-r--r--src/widgets/dialogs/qfilesystemmodel_p.h2
-rw-r--r--src/widgets/dialogs/qfontdialog.cpp28
-rw-r--r--src/widgets/dialogs/qfontdialog.h6
-rw-r--r--src/widgets/dialogs/qinputdialog.cpp112
-rw-r--r--src/widgets/dialogs/qinputdialog.h9
-rw-r--r--src/widgets/dialogs/qmessagebox.cpp124
-rw-r--r--src/widgets/doc/qtwidgets.qdocconf3
-rw-r--r--src/widgets/doc/src/qtwidgets-examples.qdoc2
-rw-r--r--src/widgets/doc/src/qtwidgets.qdoc1
-rw-r--r--src/widgets/graphicsview/qgridlayoutengine.cpp9
-rw-r--r--src/widgets/itemviews/itemviews.pri1
-rw-r--r--src/widgets/itemviews/qabstractitemview.cpp20
-rw-r--r--src/widgets/itemviews/qabstractitemview_p.h2
-rw-r--r--src/widgets/itemviews/qcolumnview.cpp11
-rw-r--r--src/widgets/itemviews/qfileiconprovider.cpp93
-rw-r--r--src/widgets/itemviews/qfileiconprovider.h14
-rw-r--r--src/widgets/itemviews/qfileiconprovider_p.h87
-rw-r--r--src/widgets/itemviews/qheaderview.cpp105
-rw-r--r--src/widgets/itemviews/qheaderview.h5
-rw-r--r--src/widgets/itemviews/qheaderview_p.h19
-rw-r--r--src/widgets/itemviews/qlistview.cpp6
-rw-r--r--src/widgets/itemviews/qlistwidget.cpp4
-rw-r--r--src/widgets/itemviews/qtableview.cpp223
-rw-r--r--src/widgets/itemviews/qtableview.h2
-rw-r--r--src/widgets/itemviews/qtableview_p.h2
-rw-r--r--src/widgets/itemviews/qtreeview.cpp199
-rw-r--r--src/widgets/itemviews/qtreeview.h5
-rw-r--r--src/widgets/itemviews/qtreeview_p.h14
-rw-r--r--src/widgets/itemviews/qtreewidget.cpp6
-rw-r--r--src/widgets/kernel/qapplication.cpp73
-rw-r--r--src/widgets/kernel/qapplication_p.h4
-rw-r--r--src/widgets/kernel/qapplication_qpa.cpp1
-rw-r--r--src/widgets/kernel/qlayout.cpp4
-rw-r--r--src/widgets/kernel/qlayoutitem.cpp2
-rw-r--r--src/widgets/kernel/qsizepolicy.h5
-rw-r--r--src/widgets/kernel/qsizepolicy.qdoc17
-rw-r--r--src/widgets/kernel/qtooltip.cpp36
-rw-r--r--src/widgets/kernel/qtooltip.h2
-rw-r--r--src/widgets/kernel/qwidget.cpp63
-rw-r--r--src/widgets/kernel/qwidget.h3
-rw-r--r--src/widgets/kernel/qwidget_p.h2
-rw-r--r--src/widgets/kernel/qwidgetwindow.cpp2
-rw-r--r--src/widgets/styles/images/cleartext-16.pngbin0 -> 760 bytes
-rw-r--r--src/widgets/styles/qcommonstyle.cpp35
-rw-r--r--src/widgets/styles/qgtkstyle_p.cpp3
-rw-r--r--src/widgets/styles/qstyle.cpp14
-rw-r--r--src/widgets/styles/qstyle.h5
-rw-r--r--src/widgets/styles/qstyle.qrc1
-rw-r--r--src/widgets/util/qsystemtrayicon_x11.cpp150
-rw-r--r--src/widgets/util/util.pri1
-rw-r--r--src/widgets/widgets/qabstractscrollarea.cpp96
-rw-r--r--src/widgets/widgets/qabstractscrollarea.h12
-rw-r--r--src/widgets/widgets/qabstractscrollarea_p.h4
-rw-r--r--src/widgets/widgets/qcombobox.cpp33
-rw-r--r--src/widgets/widgets/qcombobox.h3
-rw-r--r--src/widgets/widgets/qcombobox_p.h4
-rw-r--r--src/widgets/widgets/qdialogbuttonbox.cpp15
-rw-r--r--src/widgets/widgets/qdialogbuttonbox.h3
-rw-r--r--src/widgets/widgets/qfontcombobox.cpp99
-rw-r--r--src/widgets/widgets/qlineedit.cpp124
-rw-r--r--src/widgets/widgets/qlineedit.h25
-rw-r--r--src/widgets/widgets/qlineedit_p.cpp171
-rw-r--r--src/widgets/widgets/qlineedit_p.h82
-rw-r--r--src/widgets/widgets/qpushbutton_p.h5
-rw-r--r--src/widgets/widgets/qscrollarea.cpp12
-rw-r--r--src/widgets/widgets/qscrollarea.h2
-rw-r--r--src/widgets/widgets/qscrollbar.cpp5
-rw-r--r--src/widgets/widgets/qspinbox.cpp64
-rw-r--r--src/widgets/widgets/qspinbox.h3
-rw-r--r--src/widgets/widgets/qsplashscreen.cpp16
-rw-r--r--src/widgets/widgets/qsplashscreen.h1
-rw-r--r--src/widgets/widgets/qsplitter.cpp19
-rw-r--r--src/widgets/widgets/qsplitter_p.h3
-rw-r--r--src/widgets/widgets/qtabbar.cpp46
-rw-r--r--src/widgets/widgets/qtabbar.h3
-rw-r--r--src/widgets/widgets/qtabbar_p.h5
-rw-r--r--src/widgets/widgets/qtabwidget.cpp24
-rw-r--r--src/widgets/widgets/qtabwidget.h2
-rw-r--r--src/widgets/widgets/qtextedit.cpp36
-rw-r--r--src/widgets/widgets/qtextedit.h4
-rw-r--r--src/widgets/widgets/qtextedit_p.h2
-rw-r--r--src/widgets/widgets/qwidgetanimator.cpp28
-rw-r--r--src/widgets/widgets/qwidgetlinecontrol.cpp4
-rw-r--r--src/widgets/widgets/qwidgettextcontrol.cpp13
95 files changed, 2778 insertions, 518 deletions
diff --git a/src/widgets/dialogs/qcolordialog.cpp b/src/widgets/dialogs/qcolordialog.cpp
index c08a034d9e..5da41aa0a5 100644
--- a/src/widgets/dialogs/qcolordialog.cpp
+++ b/src/widgets/dialogs/qcolordialog.cpp
@@ -63,6 +63,8 @@
#include "qmimedata.h"
#include "qspinbox.h"
#include "qdialogbuttonbox.h"
+#include "qscreen.h"
+#include "qcursor.h"
QT_BEGIN_NAMESPACE
@@ -920,6 +922,8 @@ signals:
private slots:
void rgbEd();
void hsvEd();
+ void htmlEd();
+
private:
void showCurrentColor();
int hue, sat, val;
@@ -931,6 +935,7 @@ private:
QLabel *lblRed;
QLabel *lblGreen;
QLabel *lblBlue;
+ QLabel *lblHtml;
QColSpinBox *hEd;
QColSpinBox *sEd;
QColSpinBox *vEd;
@@ -939,6 +944,7 @@ private:
QColSpinBox *bEd;
QColSpinBox *alphaEd;
QLabel *alphaLab;
+ QLineEdit *htEd;
QColorShowLabel *lab;
bool rgbOriginal;
QColorDialog *colorDialog;
@@ -1230,6 +1236,19 @@ QColorShower::QColorShower(QColorDialog *parent)
#endif
alphaEd->hide();
alphaLab->hide();
+ lblHtml = new QLabel(this);
+ htEd = new QLineEdit(this);
+#ifndef QT_NO_SHORTCUT
+ lblHtml->setBuddy(htEd);
+#endif
+
+ QRegularExpression regExp(QStringLiteral("#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})"));
+ QRegularExpressionValidator *validator = new QRegularExpressionValidator(regExp, this);
+ htEd->setValidator(validator);
+
+ lblHtml->setAlignment(Qt::AlignRight|Qt::AlignVCenter);
+ gl->addWidget(lblHtml, 5, 1);
+ gl->addWidget(htEd, 5, 2);
connect(hEd, SIGNAL(valueChanged(int)), this, SLOT(hsvEd()));
connect(sEd, SIGNAL(valueChanged(int)), this, SLOT(hsvEd()));
@@ -1239,6 +1258,7 @@ QColorShower::QColorShower(QColorDialog *parent)
connect(gEd, SIGNAL(valueChanged(int)), this, SLOT(rgbEd()));
connect(bEd, SIGNAL(valueChanged(int)), this, SLOT(rgbEd()));
connect(alphaEd, SIGNAL(valueChanged(int)), this, SLOT(rgbEd()));
+ connect(htEd, SIGNAL(textEdited(QString)), this, SLOT(htmlEd()));
retranslateStrings();
}
@@ -1251,7 +1271,7 @@ inline bool QColorDialogPrivate::isAlphaVisible() const { return cs->isAlphaVisi
QColor QColorDialogPrivate::currentQColor() const
{
- if (!options->testOption(QColorDialogOptions::DontUseNativeDialog) && nativeDialogInUse)
+ if (nativeDialogInUse)
return platformColorDialogHelper()->currentColor();
return cs->currentQColor();
}
@@ -1273,6 +1293,8 @@ void QColorShower::rgbEd()
sEd->setValue(sat);
vEd->setValue(val);
+ htEd->setText(QColor(curCol).name());
+
showCurrentColor();
emit newCol(currentColor());
updateQColor();
@@ -1293,6 +1315,31 @@ void QColorShower::hsvEd()
gEd->setValue(qGreen(currentColor()));
bEd->setValue(qBlue(currentColor()));
+ htEd->setText(c.name());
+
+ showCurrentColor();
+ emit newCol(currentColor());
+ updateQColor();
+}
+
+void QColorShower::htmlEd()
+{
+ QColor c;
+ QString t = htEd->text();
+ c.setNamedColor(t);
+ if (!c.isValid())
+ return;
+ curCol = qRgba(c.red(), c.green(), c.blue(), currentAlpha());
+ rgb2hsv(curCol, hue, sat, val);
+
+ hEd->setValue(hue);
+ sEd->setValue(sat);
+ vEd->setValue(val);
+
+ rEd->setValue(qRed(currentColor()));
+ gEd->setValue(qGreen(currentColor()));
+ bEd->setValue(qBlue(currentColor()));
+
showCurrentColor();
emit newCol(currentColor());
updateQColor();
@@ -1313,6 +1360,8 @@ void QColorShower::setRgb(QRgb rgb)
gEd->setValue(qGreen(currentColor()));
bEd->setValue(qBlue(currentColor()));
+ htEd->setText(QColor(rgb).name());
+
showCurrentColor();
updateQColor();
}
@@ -1336,6 +1385,8 @@ void QColorShower::setHsv(int h, int s, int v)
gEd->setValue(qGreen(currentColor()));
bEd->setValue(qBlue(currentColor()));
+ htEd->setText(c.name());
+
showCurrentColor();
updateQColor();
}
@@ -1349,6 +1400,7 @@ void QColorShower::retranslateStrings()
lblGreen->setText(QColorDialog::tr("&Green:"));
lblBlue->setText(QColorDialog::tr("Bl&ue:"));
alphaLab->setText(QColorDialog::tr("A&lpha channel:"));
+ lblHtml->setText(QColorDialog::tr("&HTML:"));
}
void QColorShower::updateQColor()
@@ -1362,16 +1414,20 @@ void QColorShower::updateQColor()
//sets all widgets to display h,s,v
void QColorDialogPrivate::_q_newHsv(int h, int s, int v)
{
- cs->setHsv(h, s, v);
- cp->setCol(h, s);
- lp->setCol(h, s, v);
+ if (!nativeDialogInUse) {
+ cs->setHsv(h, s, v);
+ cp->setCol(h, s);
+ lp->setCol(h, s, v);
+ }
}
//sets all widgets to display rgb
void QColorDialogPrivate::setCurrentColor(QRgb rgb)
{
- cs->setRgb(rgb);
- _q_newColorTypedIn(rgb);
+ if (!nativeDialogInUse) {
+ cs->setRgb(rgb);
+ _q_newColorTypedIn(rgb);
+ }
}
// hack; doesn't keep curCol in sync, so use with care
@@ -1421,13 +1477,24 @@ bool QColorDialogPrivate::selectColor(const QColor &col)
return false;
}
+QColor QColorDialogPrivate::grabScreenColor(const QPoint &p)
+{
+ const QDesktopWidget *desktop = QApplication::desktop();
+ const QPixmap pixmap = QGuiApplication::screens().at(desktop->screenNumber())->grabWindow(desktop->winId(),
+ p.x(), p.y(), 1, 1);
+ QImage i = pixmap.toImage();
+ return i.pixel(0, 0);
+}
+
//sets all widgets except cs to display rgb
void QColorDialogPrivate::_q_newColorTypedIn(QRgb rgb)
{
- int h, s, v;
- rgb2hsv(rgb, h, s, v);
- cp->setCol(h, s);
- lp->setCol(h, s, v);
+ if (!nativeDialogInUse) {
+ int h, s, v;
+ rgb2hsv(rgb, h, s, v);
+ cp->setCol(h, s);
+ lp->setCol(h, s, v);
+ }
}
void QColorDialogPrivate::_q_nextCustom(int r, int c)
@@ -1450,6 +1517,48 @@ void QColorDialogPrivate::_q_newStandard(int r, int c)
custom->setSelected(-1,-1);
}
+void QColorDialogPrivate::_q_pickScreenColor()
+{
+ Q_Q(QColorDialog);
+ screenColorPicking = true;
+ // If user pushes Escape, the last color before picking will be restored.
+ beforeScreenColorPicking = cs->currentColor();
+ /*For some reason, q->grabMouse(Qt::CrossCursor) doesn't change
+ * the cursor, and therefore I have to change it manually.
+ */
+ q->grabMouse();
+ q->setCursor(Qt::CrossCursor);
+ q->grabKeyboard();
+ /* With setMouseTracking(true) the desired color can be more precisedly picked up,
+ * and continuously pushing the mouse button is not necessary.
+ */
+ q->setMouseTracking(true);
+
+ addCusBt->setDisabled(true);
+ buttons->setDisabled(true);
+ screenColorPickerButton->setDisabled(true);
+
+ q->setCurrentColor(grabScreenColor(QCursor::pos()));
+ lblScreenColorInfo->setText(QColorDialog::tr("Cursor at %1, %2, color: %3\nPress ESC to cancel")
+ .arg(QCursor::pos().x())
+ .arg(QCursor::pos().y())
+ .arg(q->currentColor().name()));
+}
+
+void QColorDialogPrivate::releaseColorPicking()
+{
+ Q_Q(QColorDialog);
+ screenColorPicking = false;
+ q->releaseMouse();
+ q->releaseKeyboard();
+ q->setCursor(Qt::ArrowCursor);
+ q->setMouseTracking(false);
+ lblScreenColorInfo->setText(QLatin1String("\n"));
+ addCusBt->setDisabled(false);
+ buttons->setDisabled(false);
+ screenColorPickerButton->setDisabled(false);
+}
+
void QColorDialogPrivate::init(const QColor &initial)
{
Q_Q(QColorDialog);
@@ -1457,9 +1566,24 @@ void QColorDialogPrivate::init(const QColor &initial)
q->setSizeGripEnabled(false);
q->setWindowTitle(QColorDialog::tr("Select Color"));
+ // default: use the native dialog if possible. Can be overridden in setOptions()
nativeDialogInUse = (platformColorDialogHelper() != 0);
-
+ screenColorPicking = false;
nextCust = 0;
+
+ if (!nativeDialogInUse)
+ initWidgets();
+
+#ifdef Q_WS_MAC
+ delegate = 0;
+#endif
+
+ q->setCurrentColor(initial);
+}
+
+void QColorDialogPrivate::initWidgets()
+{
+ Q_Q(QColorDialog);
QVBoxLayout *mainLay = new QVBoxLayout(q);
// there's nothing in this dialog that benefits from sizing up
mainLay->setSizeConstraint(QLayout::SetFixedSize);
@@ -1494,6 +1618,15 @@ void QColorDialogPrivate::init(const QColor &initial)
leftLay->addWidget(lblBasicColors);
leftLay->addWidget(standard);
+#if !defined(Q_OS_WINCE) && !defined(QT_SMALL_COLORDIALOG)
+ // The screen color picker button
+ screenColorPickerButton = new QPushButton(QColorDialog::tr("Pick Screen Color"));
+ leftLay->addWidget(screenColorPickerButton);
+ lblScreenColorInfo = new QLabel(QLatin1String("\n"));
+ leftLay->addWidget(lblScreenColorInfo);
+ q->connect(screenColorPickerButton, SIGNAL(clicked()), SLOT(_q_pickScreenColor()));
+#endif
+
#if !defined(Q_OS_WINCE)
leftLay->addStretch();
#endif
@@ -1597,12 +1730,6 @@ void QColorDialogPrivate::init(const QColor &initial)
QObject::connect(cancel, SIGNAL(clicked()), q, SLOT(reject()));
retranslateStrings();
-
-#ifdef Q_WS_MAC
- delegate = 0;
-#endif
-
- q->setCurrentColor(initial);
}
void QColorDialogPrivate::initHelper(QPlatformDialogHelper *h)
@@ -1667,6 +1794,11 @@ static const Qt::WindowFlags DefaultWindowFlags =
during the execution of the program. Use setCustomColor() to set
the custom colors, and use customColor() to get them.
+ When pressing the "Pick Screen Color" button, the cursor changes to a haircross
+ and the colors on the screen are scanned. The user can pick up one by clicking
+ the mouse or the Enter button. Pressing Escape restores the last color selected
+ before entering this mode.
+
The \l{dialogs/standarddialogs}{Standard Dialogs} example shows
how to use QColorDialog as well as other built-in Qt dialogs.
@@ -1708,12 +1840,13 @@ QColorDialog::QColorDialog(const QColor &initial, QWidget *parent)
void QColorDialog::setCurrentColor(const QColor &color)
{
Q_D(QColorDialog);
- d->setCurrentColor(color.rgb());
- d->selectColor(color);
- d->setCurrentAlpha(color.alpha());
-
- if (!testOption(QColorDialog::DontUseNativeDialog) && d->nativeDialogInUse)
+ if (d->nativeDialogInUse)
d->platformColorDialogHelper()->setCurrentColor(color);
+ else {
+ d->setCurrentColor(color.rgb());
+ d->selectColor(color);
+ d->setCurrentAlpha(color.alpha());
+ }
}
QColor QColorDialog::currentColor() const
@@ -1783,10 +1916,14 @@ void QColorDialog::setOptions(ColorDialogOptions options)
return;
d->options->setOptions(QColorDialogOptions::ColorDialogOptions(int(options)));
- d->buttons->setVisible(!(options & NoButtons));
- d->showAlpha(options & ShowAlphaChannel);
- if (options & DontUseNativeDialog)
+ if ((options & DontUseNativeDialog) && d->nativeDialogInUse) {
d->nativeDialogInUse = false;
+ d->initWidgets();
+ }
+ if (!d->nativeDialogInUse) {
+ d->buttons->setVisible(!(options & NoButtons));
+ d->showAlpha(options & ShowAlphaChannel);
+ }
}
QColorDialog::ColorDialogOptions QColorDialog::options() const
@@ -1868,7 +2005,7 @@ void QColorDialog::setVisible(bool visible)
}
#else
- if (!(options() & DontUseNativeDialog) && d->nativeDialogInUse) {
+ if (d->nativeDialogInUse) {
d->setNativeDialogVisible(visible);
// Set WA_DontShowOnScreen so that QDialog::setVisible(visible) below
// updates the state correctly, but skips showing the non-native version:
@@ -1983,6 +2120,57 @@ void QColorDialog::changeEvent(QEvent *e)
}
/*!
+ \reimp
+*/
+void QColorDialog::mouseMoveEvent(QMouseEvent *e)
+{
+ Q_D(QColorDialog);
+ if (d->screenColorPicking) {
+ setCurrentColor(d->grabScreenColor(e->globalPos()));
+ d->lblScreenColorInfo->setText(QColorDialog::tr("Cursor at %1, %2, color: %3\nPress ESC to cancel")
+ .arg(e->globalPos().x())
+ .arg(e->globalPos().y())
+ .arg(currentColor().name()));
+ return;
+ }
+ QDialog::mouseMoveEvent(e);
+}
+
+/*!
+ \reimp
+*/
+void QColorDialog::mouseReleaseEvent(QMouseEvent *e)
+{
+ Q_D(QColorDialog);
+ if (d->screenColorPicking) {
+ setCurrentColor(d->grabScreenColor(e->globalPos()));
+ d->releaseColorPicking();
+ return;
+ }
+ QDialog::mouseReleaseEvent(e);
+}
+
+/*!
+ \reimp
+*/
+void QColorDialog::keyPressEvent(QKeyEvent *e)
+{
+ Q_D(QColorDialog);
+ if (d->screenColorPicking) {
+ if (e->key() == Qt::Key_Escape) {
+ d->releaseColorPicking();
+ d->setCurrentColor(d->beforeScreenColorPicking);
+ } else if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) {
+ setCurrentColor(d->grabScreenColor(QCursor::pos()));
+ d->releaseColorPicking();
+ }
+ e->accept();
+ return;
+ }
+ QDialog::keyPressEvent(e);
+}
+
+/*!
Closes the dialog and sets its result code to \a result. If this dialog
is shown with exec(), done() causes the local event loop to finish,
and exec() to return \a result.
diff --git a/src/widgets/dialogs/qcolordialog.h b/src/widgets/dialogs/qcolordialog.h
index f6dc627a05..c7a1d6f400 100644
--- a/src/widgets/dialogs/qcolordialog.h
+++ b/src/widgets/dialogs/qcolordialog.h
@@ -112,6 +112,9 @@ Q_SIGNALS:
protected:
void changeEvent(QEvent *event);
+ virtual void mouseMoveEvent(QMouseEvent *);
+ virtual void mouseReleaseEvent(QMouseEvent *);
+ virtual void keyPressEvent(QKeyEvent *);
void done(int result);
private:
@@ -123,6 +126,7 @@ private:
Q_PRIVATE_SLOT(d_func(), void _q_nextCustom(int, int))
Q_PRIVATE_SLOT(d_func(), void _q_newCustom(int, int))
Q_PRIVATE_SLOT(d_func(), void _q_newStandard(int, int))
+ Q_PRIVATE_SLOT(d_func(), void _q_pickScreenColor())
friend class QColorShower;
};
diff --git a/src/widgets/dialogs/qcolordialog_p.h b/src/widgets/dialogs/qcolordialog_p.h
index 695e95d26c..08199cc7c1 100644
--- a/src/widgets/dialogs/qcolordialog_p.h
+++ b/src/widgets/dialogs/qcolordialog_p.h
@@ -82,11 +82,13 @@ public:
{ return static_cast<QPlatformColorDialogHelper *>(platformHelper()); }
void init(const QColor &initial);
+ void initWidgets();
QRgb currentColor() const;
QColor currentQColor() const;
void setCurrentColor(QRgb rgb);
void setCurrentQColor(const QColor &color);
bool selectColor(const QColor &color);
+ QColor grabScreenColor(const QPoint &p);
int currentAlpha() const;
void setCurrentAlpha(int a);
@@ -101,6 +103,8 @@ public:
void _q_nextCustom(int, int);
void _q_newCustom(int, int);
void _q_newStandard(int, int);
+ void _q_pickScreenColor();
+ void releaseColorPicking();
QWellArray *custom;
QWellArray *standard;
@@ -112,12 +116,16 @@ public:
QColorShower *cs;
QLabel *lblBasicColors;
QLabel *lblCustomColors;
+ QLabel *lblScreenColorInfo;
QPushButton *ok;
QPushButton *cancel;
QPushButton *addCusBt;
+ QPushButton *screenColorPickerButton;
QColor selectedQColor;
int nextCust;
bool smallDisplay;
+ bool screenColorPicking;
+ QRgb beforeScreenColorPicking;
QSharedPointer<QColorDialogOptions> options;
QPointer<QObject> receiverToDisconnectOnClose;
diff --git a/src/widgets/dialogs/qdialog.cpp b/src/widgets/dialogs/qdialog.cpp
index 2cda99a269..e1097dd1bb 100644
--- a/src/widgets/dialogs/qdialog.cpp
+++ b/src/widgets/dialogs/qdialog.cpp
@@ -767,8 +767,10 @@ void QDialog::setVisible(bool visible)
if (d->eventLoop)
d->eventLoop->exit();
}
+
+ const QPlatformTheme *theme = QGuiApplicationPrivate::platformTheme();
if (d->mainDef && isActiveWindow()
- && d->styleHint(QPlatformDialogHelper::SnapToDefaultButton).toBool())
+ && theme->themeHint(QPlatformTheme::DialogSnapToDefaultButton).toBool())
QCursor::setPos(d->mainDef->mapToGlobal(d->mainDef->rect().center()));
}
diff --git a/src/widgets/dialogs/qdialog_p.h b/src/widgets/dialogs/qdialog_p.h
index eb0cb2372b..5064efa35d 100644
--- a/src/widgets/dialogs/qdialog_p.h
+++ b/src/widgets/dialogs/qdialog_p.h
@@ -111,7 +111,7 @@ public:
QPointer<QEventLoop> eventLoop;
- bool nativeDialogInUse; // Assigned in setVisible_sys() in derived classes.
+ bool nativeDialogInUse;
QPlatformDialogHelper *platformHelper() const;
private:
diff --git a/src/widgets/dialogs/qfiledialog.cpp b/src/widgets/dialogs/qfiledialog.cpp
index c42752311f..9c4b99253a 100644
--- a/src/widgets/dialogs/qfiledialog.cpp
+++ b/src/widgets/dialogs/qfiledialog.cpp
@@ -86,15 +86,27 @@ Q_GLOBAL_STATIC(QString, lastVisitedDir)
typedef QString (*_qt_filedialog_existing_directory_hook)(QWidget *parent, const QString &caption, const QString &dir, QFileDialog::Options options);
Q_WIDGETS_EXPORT _qt_filedialog_existing_directory_hook qt_filedialog_existing_directory_hook = 0;
+typedef QUrl (*_qt_filedialog_existing_directory_url_hook)(QWidget *parent, const QString &caption, const QUrl &dir, QFileDialog::Options options, const QStringList &supportedSchemes);
+Q_WIDGETS_EXPORT _qt_filedialog_existing_directory_url_hook qt_filedialog_existing_directory_url_hook = 0;
+
typedef QString (*_qt_filedialog_open_filename_hook)(QWidget * parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options);
Q_WIDGETS_EXPORT _qt_filedialog_open_filename_hook qt_filedialog_open_filename_hook = 0;
+typedef QUrl (*_qt_filedialog_open_file_url_hook)(QWidget * parent, const QString &caption, const QUrl &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options, const QStringList &supportedSchemes);
+Q_WIDGETS_EXPORT _qt_filedialog_open_file_url_hook qt_filedialog_open_file_url_hook = 0;
+
typedef QStringList (*_qt_filedialog_open_filenames_hook)(QWidget * parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options);
Q_WIDGETS_EXPORT _qt_filedialog_open_filenames_hook qt_filedialog_open_filenames_hook = 0;
+typedef QList<QUrl> (*_qt_filedialog_open_file_urls_hook)(QWidget * parent, const QString &caption, const QUrl &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options, const QStringList &supportedSchemes);
+Q_WIDGETS_EXPORT _qt_filedialog_open_file_urls_hook qt_filedialog_open_file_urls_hook = 0;
+
typedef QString (*_qt_filedialog_save_filename_hook)(QWidget * parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options);
Q_WIDGETS_EXPORT _qt_filedialog_save_filename_hook qt_filedialog_save_filename_hook = 0;
+typedef QUrl (*_qt_filedialog_save_file_url_hook)(QWidget * parent, const QString &caption, const QUrl &dir, const QString &filter, QString *selectedFilter, QFileDialog::Options options, const QStringList &supportedSchemes);
+Q_WIDGETS_EXPORT _qt_filedialog_save_file_url_hook qt_filedialog_save_file_url_hook = 0;
+
/*!
\class QFileDialog
\brief The QFileDialog class provides a dialog that allow users to select files or directories.
@@ -243,6 +255,11 @@ Q_WIDGETS_EXPORT _qt_filedialog_save_filename_hook qt_filedialog_save_filename_h
static functions will always be an application modal dialog. If
you want to use sheets, use QFileDialog::open() instead.
+ \value DontUseCustomDirectoryIcons Always use the default directory icon.
+ Some platforms allow the user to set a different icon. Custom icon lookup
+ cause a big performance impact over network or removable drives.
+ Setting this will enable the QFileIconProvider::DontUseCustomDirectoryIcons
+ option in the icon provider. This enum value was added in Qt 5.2.
*/
/*!
@@ -258,37 +275,76 @@ Q_WIDGETS_EXPORT _qt_filedialog_save_filename_hook qt_filedialog_save_filename_h
/*!
\fn void QFileDialog::filesSelected(const QStringList &selected)
- When the selection changes and the dialog is accepted, this signal is
- emitted with the (possibly empty) list of \a selected files.
+ When the selection changes for local operations and the dialog is
+ accepted, this signal is emitted with the (possibly empty) list
+ of \a selected files.
\sa currentChanged(), QDialog::Accepted
*/
+/*!
+ \fn void QFileDialog::urlsSelected(const QList<QUrl> &urls)
+
+ When the selection changes and the dialog is accepted, this signal is
+ emitted with the (possibly empty) list of selected \a urls.
+
+ \sa currentUrlChanged(), QDialog::Accepted
+ \since 5.2
+*/
/*!
\fn void QFileDialog::fileSelected(const QString &file)
- When the selection changes and the dialog is accepted, this signal is
- emitted with the (possibly empty) selected \a file.
+ When the selection changes for local operations and the dialog is
+ accepted, this signal is emitted with the (possibly empty)
+ selected \a file.
\sa currentChanged(), QDialog::Accepted
*/
+/*!
+ \fn void QFileDialog::urlSelected(const QUrl &url)
+
+ When the selection changes and the dialog is accepted, this signal is
+ emitted with the (possibly empty) selected \a url.
+
+ \sa currentUrlChanged(), QDialog::Accepted
+ \since 5.2
+*/
/*!
\fn void QFileDialog::currentChanged(const QString &path)
- When the current file changes, this signal is emitted with the
- new file name as the \a path parameter.
+ When the current file changes for local operations, this signal is
+ emitted with the new file name as the \a path parameter.
\sa filesSelected()
*/
/*!
+ \fn void QFileDialog::currentUrlChanged(const QUrl &url)
+
+ When the current file changes, this signal is emitted with the
+ new file URL as the \a url parameter.
+
+ \sa urlsSelected()
+ \since 5.2
+*/
+
+/*!
\fn void QFileDialog::directoryEntered(const QString &directory)
\since 4.3
+ This signal is emitted for local operations when the user enters
+ a \a directory.
+*/
+
+/*!
+ \fn void QFileDialog::directoryUrlEntered(const QUrl &directory)
+
This signal is emitted when the user enters a \a directory.
+
+ \since 5.2
*/
/*!
@@ -532,11 +588,10 @@ QFileDialogPrivate::~QFileDialogPrivate()
void QFileDialogPrivate::initHelper(QPlatformDialogHelper *h)
{
QFileDialog *d = q_func();
- QObject::connect(h, SIGNAL(fileSelected(QString)), d, SIGNAL(fileSelected(QString)));
- QObject::connect(h, SIGNAL(filesSelected(QStringList)), d, SIGNAL(filesSelected(QStringList)));
- QObject::connect(h, SIGNAL(currentChanged(QString)), d, SIGNAL(currentChanged(QString)));
- QObject::connect(h, SIGNAL(directoryEntered(QString)), d, SIGNAL(directoryEntered(QString)));
- QObject::connect(h, SIGNAL(directoryEntered(QString)), d, SLOT(_q_nativeEnterDirectory(QString)));
+ QObject::connect(h, SIGNAL(fileSelected(QUrl)), d, SLOT(_q_nativeFileSelected(QUrl)));
+ QObject::connect(h, SIGNAL(filesSelected(QList<QUrl>)), d, SLOT(_q_nativeFilesSelected(QList<QUrl>)));
+ QObject::connect(h, SIGNAL(currentChanged(QUrl)), d, SLOT(_q_nativeCurrentChanged(QUrl)));
+ QObject::connect(h, SIGNAL(directoryEntered(QUrl)), d, SLOT(_q_nativeEnterDirectory(QUrl)));
QObject::connect(h, SIGNAL(filterSelected(QString)), d, SIGNAL(filterSelected(QString)));
static_cast<QPlatformFileDialogHelper *>(h)->setOptions(options);
}
@@ -550,8 +605,8 @@ void QFileDialogPrivate::helperPrepareShow(QPlatformDialogHelper *)
options->setSidebarUrls(qFileDialogUi->sidebar->urls());
const QDir directory = q->directory();
options->setInitialDirectory(directory.exists() ?
- directory.absolutePath() :
- QString());
+ QUrl::fromLocalFile(directory.absolutePath()) :
+ QUrl());
options->setInitiallySelectedNameFilter(q->selectedNameFilter());
options->setInitiallySelectedFiles(userSelectedFiles());
}
@@ -742,6 +797,15 @@ void QFileDialog::setOptions(Options options)
if (changed & ShowDirsOnly)
setFilter((options & ShowDirsOnly) ? filter() & ~QDir::Files : filter() | QDir::Files);
+
+ if (changed & DontUseCustomDirectoryIcons) {
+ QFileIconProvider::Options providerOptions = iconProvider()->options();
+ if (options & DontUseCustomDirectoryIcons)
+ providerOptions |= QFileIconProvider::DontUseCustomDirectoryIcons;
+ else
+ providerOptions &= ~QFileIconProvider::DontUseCustomDirectoryIcons;
+ iconProvider()->setOptions(providerOptions);
+ }
}
QFileDialog::Options QFileDialog::options() const
@@ -850,7 +914,7 @@ void QFileDialog::setDirectory(const QString &directory)
d->setLastVisitedDirectory(newDirectory);
if (d->nativeDialogInUse){
- d->setDirectory_sys(newDirectory);
+ d->setDirectory_sys(QUrl::fromLocalFile(newDirectory));
return;
}
if (d->rootPath() == newDirectory)
@@ -875,7 +939,42 @@ void QFileDialog::setDirectory(const QString &directory)
QDir QFileDialog::directory() const
{
Q_D(const QFileDialog);
- return QDir(d->nativeDialogInUse ? d->directory_sys() : d->rootPath());
+ return QDir(d->nativeDialogInUse ? d->directory_sys().toLocalFile() : d->rootPath());
+}
+
+/*!
+ Sets the file dialog's current \a directory url.
+
+ \note The non-native QFileDialog supports only local files.
+
+ \since 5.2
+*/
+void QFileDialog::setDirectoryUrl(const QUrl &directory)
+{
+ Q_D(QFileDialog);
+ if (!directory.isValid())
+ return;
+
+ if (d->nativeDialogInUse)
+ d->setDirectory_sys(directory);
+ else if (directory.isLocalFile())
+ setDirectory(directory.toLocalFile());
+ else
+ qWarning() << "Non-native QFileDialog supports only local files";
+}
+
+/*!
+ Returns the url of the directory currently being displayed in the dialog.
+
+ \since 5.2
+*/
+QUrl QFileDialog::directoryUrl() const
+{
+ Q_D(const QFileDialog);
+ if (d->nativeDialogInUse)
+ return d->directory_sys();
+ else
+ return QUrl::fromLocalFile(directory().absolutePath());
}
/*!
@@ -890,7 +989,7 @@ void QFileDialog::selectFile(const QString &filename)
return;
if (d->nativeDialogInUse){
- d->selectFile_sys(filename);
+ d->selectFile_sys(QUrl::fromLocalFile(filename));
return;
}
@@ -927,6 +1026,28 @@ void QFileDialog::selectFile(const QString &filename)
d->lineEdit()->setText(file);
}
+/*!
+ Selects the given \a url in the file dialog.
+
+ \note The non-native QFileDialog supports only local files.
+
+ \sa selectedUrls()
+ \since 5.2
+*/
+void QFileDialog::selectUrl(const QUrl &url)
+{
+ Q_D(QFileDialog);
+ if (!url.isValid())
+ return;
+
+ if (d->nativeDialogInUse)
+ d->selectFile_sys(url);
+ else if (url.isLocalFile())
+ selectFile(url.toLocalFile());
+ else
+ qWarning() << "Non-native QFileDialog supports only local files";
+}
+
#ifdef Q_OS_UNIX
Q_AUTOTEST_EXPORT QString qt_tildeExpansion(const QString &path, bool *expanded = 0)
{
@@ -1015,17 +1136,19 @@ QStringList QFileDialogPrivate::typedFiles() const
// Return selected files without defaulting to the root of the file system model
// used for initializing QFileDialogOptions for native dialogs. The default is
// not suitable for native dialogs since it mostly equals directory().
-QStringList QFileDialogPrivate::userSelectedFiles() const
+QList<QUrl> QFileDialogPrivate::userSelectedFiles() const
{
+ QList<QUrl> files;
+
if (nativeDialogInUse)
- return addDefaultSuffixToFiles(selectedFiles_sys());
+ return addDefaultSuffixToUrls(selectedFiles_sys());
- QStringList files;
foreach (const QModelIndex &index, qFileDialogUi->listView->selectionModel()->selectedRows())
- files.append(index.data(QFileSystemModel::FilePathRole).toString());
+ files.append(QUrl::fromLocalFile(index.data(QFileSystemModel::FilePathRole).toString()));
if (files.isEmpty() && !lineEdit()->text().isEmpty())
- files = typedFiles();
+ foreach (const QString &path, typedFiles())
+ files.append(QUrl::fromLocalFile(path));
return files;
}
@@ -1056,6 +1179,20 @@ QStringList QFileDialogPrivate::addDefaultSuffixToFiles(const QStringList filesT
return files;
}
+QList<QUrl> QFileDialogPrivate::addDefaultSuffixToUrls(const QList<QUrl> &urlsToFix) const
+{
+ QList<QUrl> urls;
+ for (int i=0; i<urlsToFix.size(); ++i) {
+ QUrl url = urlsToFix.at(i);
+ // if the filename has no suffix, add the default suffix
+ const QString defaultSuffix = options->defaultSuffix();
+ if (!defaultSuffix.isEmpty() && !url.path().endsWith(QLatin1Char('/')) && url.path().lastIndexOf(QLatin1Char('.')) == -1)
+ url.setPath(url.path() + QLatin1Char('.') + defaultSuffix);
+ urls.append(url);
+ }
+ return urls;
+}
+
/*!
Returns a list of strings containing the absolute paths of the
@@ -1068,7 +1205,9 @@ QStringList QFileDialog::selectedFiles() const
{
Q_D(const QFileDialog);
- QStringList files = d->userSelectedFiles();
+ QStringList files;
+ foreach (const QUrl &file, d->userSelectedFiles())
+ files.append(file.toLocalFile());
if (files.isEmpty()) {
const FileMode fm = fileMode();
if (fm != ExistingFile && fm != ExistingFiles)
@@ -1077,6 +1216,27 @@ QStringList QFileDialog::selectedFiles() const
return files;
}
+/*!
+ Returns a list of urls containing the selected files in the dialog.
+ If no files are selected, or the mode is not ExistingFiles or
+ ExistingFile, selectedUrls() contains the current path in the viewport.
+
+ \sa selectedNameFilter(), selectUrl()
+ \since 5.2
+*/
+QList<QUrl> QFileDialog::selectedUrls() const
+{
+ Q_D(const QFileDialog);
+ if (d->nativeDialogInUse) {
+ return d->userSelectedFiles();
+ } else {
+ QList<QUrl> urls;
+ foreach (const QString &file, selectedFiles())
+ urls.append(QUrl::fromLocalFile(file));
+ return urls;
+ }
+}
+
/*
Makes a list of filters from ;;-separated text.
Used by the mac and windows implementations
@@ -1526,6 +1686,8 @@ bool QFileDialog::confirmOverwrite() const
filename if it has no suffix already. The suffix is typically
used to indicate the file type (e.g. "txt" indicates a text
file).
+
+ If the first character is a dot ('.'), it is removed.
*/
void QFileDialog::setDefaultSuffix(const QString &suffix)
{
@@ -1798,6 +1960,48 @@ QString QFileDialog::getOpenFileName(QWidget *parent,
}
/*!
+ This is a convenience static function that returns an existing file
+ selected by the user. If the user presses Cancel, it returns an
+ empty url.
+
+ The function is used similarly to QFileDialog::getOpenFileName(). In
+ particular \a parent, \a caption, \a dir, \a filter, \a selectedFilter
+ and \a options are used in the exact same way.
+
+ The main difference with QFileDialog::getOpenFileName() comes from
+ the ability offered to the user to select a remote file. That's why
+ the return type and the type of \a dir is QUrl.
+
+ The \a supportedSchemes argument allows to restrict the type of URLs the
+ user will be able to select. It is a way for the application to declare
+ the protocols it will support to fetch the file content. An empty list
+ means that no restriction is applied (the default).
+ Supported for local files ("file" scheme) is implicit and always enabled.
+ it is not necessary to include in the restriction.
+
+ When possible, this static function will use the native file dialog and
+ not a QFileDialog. On platforms which don't support selecting remote
+ files, Qt will allow to select only local files.
+
+ \sa getOpenFileName(), getOpenFileUrls(), getSaveFileUrl(), getExistingDirectoryUrl()
+ \since 5.2
+*/
+QUrl QFileDialog::getOpenFileUrl(QWidget *parent,
+ const QString &caption,
+ const QUrl &dir,
+ const QString &filter,
+ QString *selectedFilter,
+ Options options,
+ const QStringList &supportedSchemes)
+{
+ if (qt_filedialog_open_file_url_hook && !(options & DontUseNativeDialog))
+ return qt_filedialog_open_file_url_hook(parent, caption, dir, filter, selectedFilter, options, supportedSchemes);
+
+ // Falls back to local file
+ return QUrl::fromLocalFile(getOpenFileName(parent, caption, dir.toLocalFile(), filter, selectedFilter, options));
+}
+
+/*!
This is a convenience static function that will return one or more existing
files selected by the user.
@@ -1883,6 +2087,55 @@ QStringList QFileDialog::getOpenFileNames(QWidget *parent,
}
/*!
+ This is a convenience static function that will return or or more existing
+ files selected by the user. If the user presses Cancel, it returns an
+ empty list.
+
+ The function is used similarly to QFileDialog::getOpenFileNames(). In
+ particular \a parent, \a caption, \a dir, \a filter, \a selectedFilter
+ and \a options are used in the exact same way.
+
+ The main difference with QFileDialog::getOpenFileNames() comes from
+ the ability offered to the user to select remote files. That's why
+ the return type and the type of \a dir are respectively QList<QUrl>
+ and QUrl.
+
+ The \a supportedSchemes argument allows to restrict the type of URLs the
+ user will be able to select. It is a way for the application to declare
+ the protocols it will support to fetch the file content. An empty list
+ means that no restriction is applied (the default).
+ Supported for local files ("file" scheme) is implicit and always enabled.
+ it is not necessary to include in the restriction.
+
+ When possible, this static function will use the native file dialog and
+ not a QFileDialog. On platforms which don't support selecting remote
+ files, Qt will allow to select only local files.
+
+ \sa getOpenFileNames(), getOpenFileUrl(), getSaveFileUrl(), getExistingDirectoryUrl()
+ \since 5.2
+*/
+QList<QUrl> QFileDialog::getOpenFileUrls(QWidget *parent,
+ const QString &caption,
+ const QUrl &dir,
+ const QString &filter,
+ QString *selectedFilter,
+ Options options,
+ const QStringList &supportedSchemes)
+{
+ if (qt_filedialog_open_file_urls_hook && !(options & DontUseNativeDialog))
+ return qt_filedialog_open_file_urls_hook(parent, caption, dir, filter, selectedFilter, options, supportedSchemes);
+
+ // Falls back to local files
+ QList<QUrl> urls;
+
+ const QStringList fileNames = getOpenFileNames(parent, caption, dir.toLocalFile(), filter, selectedFilter, options);
+ foreach (const QString &fileName, fileNames)
+ urls << QUrl::fromLocalFile(fileName);
+
+ return urls;
+}
+
+/*!
This is a convenience static function that will return a file name selected
by the user. The file does not have to exist.
@@ -1971,6 +2224,48 @@ QString QFileDialog::getSaveFileName(QWidget *parent,
}
/*!
+ This is a convenience static function that returns a file selected by
+ the user. The file does not have to exist. If the user presses Cancel,
+ it returns an empty url.
+
+ The function is used similarly to QFileDialog::getSaveFileName(). In
+ particular \a parent, \a caption, \a dir, \a filter, \a selectedFilter
+ and \a options are used in the exact same way.
+
+ The main difference with QFileDialog::getSaveFileName() comes from
+ the ability offered to the user to select a remote file. That's why
+ the return type and the type of \a dir is QUrl.
+
+ The \a supportedSchemes argument allows to restrict the type of URLs the
+ user will be able to select. It is a way for the application to declare
+ the protocols it will support to save the file content. An empty list
+ means that no restriction is applied (the default).
+ Supported for local files ("file" scheme) is implicit and always enabled.
+ it is not necessary to include in the restriction.
+
+ When possible, this static function will use the native file dialog and
+ not a QFileDialog. On platforms which don't support selecting remote
+ files, Qt will allow to select only local files.
+
+ \sa getSaveFileName(), getOpenFileUrl(), getOpenFileUrls(), getExistingDirectoryUrl()
+ \since 5.2
+*/
+QUrl QFileDialog::getSaveFileUrl(QWidget *parent,
+ const QString &caption,
+ const QUrl &dir,
+ const QString &filter,
+ QString *selectedFilter,
+ Options options,
+ const QStringList &supportedSchemes)
+{
+ if (qt_filedialog_save_file_url_hook && !(options & DontUseNativeDialog))
+ return qt_filedialog_save_file_url_hook(parent, caption, dir, filter, selectedFilter, options, supportedSchemes);
+
+ // Falls back to local file
+ return QUrl::fromLocalFile(getSaveFileName(parent, caption, dir.toLocalFile(), filter, selectedFilter, options));
+}
+
+/*!
This is a convenience static function that will return an existing
directory selected by the user.
@@ -2041,6 +2336,46 @@ QString QFileDialog::getExistingDirectory(QWidget *parent,
return QString();
}
+/*!
+ This is a convenience static function that will return an existing
+ directory selected by the user. If the user presses Cancel, it
+ returns an empty url.
+
+ The function is used similarly to QFileDialog::getExistingDirectory().
+ In particular \a parent, \a caption, \a dir and \a options are used
+ in the exact same way.
+
+ The main difference with QFileDialog::getExistingDirectory() comes from
+ the ability offered to the user to select a remote directory. That's why
+ the return type and the type of \a dir is QUrl.
+
+ The \a supportedSchemes argument allows to restrict the type of URLs the
+ user will be able to select. It is a way for the application to declare
+ the protocols it will support to fetch the file content. An empty list
+ means that no restriction is applied (the default).
+ Supported for local files ("file" scheme) is implicit and always enabled.
+ it is not necessary to include in the restriction.
+
+ When possible, this static function will use the native file dialog and
+ not a QFileDialog. On platforms which don't support selecting remote
+ files, Qt will allow to select only local files.
+
+ \sa getExistingDirectory(), getOpenFileUrl(), getOpenFileUrls(), getSaveFileUrl()
+ \since 5.2
+*/
+QUrl QFileDialog::getExistingDirectoryUrl(QWidget *parent,
+ const QString &caption,
+ const QUrl &dir,
+ Options options,
+ const QStringList &supportedSchemes)
+{
+ if (qt_filedialog_existing_directory_url_hook && !(options & DontUseNativeDialog))
+ return qt_filedialog_existing_directory_url_hook(parent, caption, dir, options, supportedSchemes);
+
+ // Falls back to local file
+ return QUrl::fromLocalFile(getExistingDirectory(parent, caption, dir.toLocalFile(), options));
+}
+
inline static QString _qt_get_directory(const QString &path)
{
QFileInfo info = QFileInfo(QDir::current(), path);
@@ -3119,10 +3454,42 @@ void QFileDialogPrivate::_q_fileRenamed(const QString &path, const QString oldNa
}
}
-void QFileDialogPrivate::_q_nativeEnterDirectory(const QString &directory)
+void QFileDialogPrivate::_q_nativeFileSelected(const QUrl &file)
+{
+ Q_Q(QFileDialog);
+ emit q->urlSelected(file);
+ if (file.isLocalFile())
+ emit q->fileSelected(file.toLocalFile());
+}
+
+void QFileDialogPrivate::_q_nativeFilesSelected(const QList<QUrl> &files)
+{
+ Q_Q(QFileDialog);
+ emit q->urlsSelected(files);
+ QStringList localFiles;
+ foreach (const QUrl &file, files)
+ if (file.isLocalFile())
+ localFiles.append(file.toLocalFile());
+ if (!localFiles.isEmpty())
+ emit q->filesSelected(localFiles);
+}
+
+void QFileDialogPrivate::_q_nativeCurrentChanged(const QUrl &file)
{
- if (!directory.isEmpty()) // Windows native dialogs occasionally emit signals with empty strings.
- *lastVisitedDir() = directory;
+ Q_Q(QFileDialog);
+ emit q->currentUrlChanged(file);
+ if (file.isLocalFile())
+ emit q->currentChanged(file.toLocalFile());
+}
+
+void QFileDialogPrivate::_q_nativeEnterDirectory(const QUrl &directory)
+{
+ Q_Q(QFileDialog);
+ emit q->directoryUrlEntered(directory);
+ if (!directory.isEmpty() && directory.isLocalFile()) { // Windows native dialogs occasionally emit signals with empty strings.
+ *lastVisitedDir() = directory.toLocalFile();
+ emit q->directoryEntered(directory.toLocalFile());
+ }
}
/*!
diff --git a/src/widgets/dialogs/qfiledialog.h b/src/widgets/dialogs/qfiledialog.h
index 98d1fd5695..5413a42ea9 100644
--- a/src/widgets/dialogs/qfiledialog.h
+++ b/src/widgets/dialogs/qfiledialog.h
@@ -44,6 +44,7 @@
#include <QtCore/qdir.h>
#include <QtCore/qstring.h>
+#include <QtCore/qurl.h>
#include <QtWidgets/qdialog.h>
QT_BEGIN_NAMESPACE
@@ -58,7 +59,6 @@ class QFileIconProvider;
class QFileDialogPrivate;
class QAbstractItemDelegate;
class QAbstractProxyModel;
-class QUrl;
class Q_WIDGETS_EXPORT QFileDialog : public QDialog
{
@@ -84,13 +84,14 @@ public:
enum Option
{
- ShowDirsOnly = 0x00000001,
- DontResolveSymlinks = 0x00000002,
- DontConfirmOverwrite = 0x00000004,
- DontUseSheet = 0x00000008,
- DontUseNativeDialog = 0x00000010,
- ReadOnly = 0x00000020,
- HideNameFilterDetails = 0x00000040
+ ShowDirsOnly = 0x00000001,
+ DontResolveSymlinks = 0x00000002,
+ DontConfirmOverwrite = 0x00000004,
+ DontUseSheet = 0x00000008,
+ DontUseNativeDialog = 0x00000010,
+ ReadOnly = 0x00000020,
+ HideNameFilterDetails = 0x00000040,
+ DontUseCustomDirectoryIcons = 0x00000080
};
Q_DECLARE_FLAGS(Options, Option)
@@ -105,9 +106,15 @@ public:
inline void setDirectory(const QDir &directory);
QDir directory() const;
+ void setDirectoryUrl(const QUrl &directory);
+ QUrl directoryUrl() const;
+
void selectFile(const QString &filename);
QStringList selectedFiles() const;
+ void selectUrl(const QUrl &url);
+ QList<QUrl> selectedUrls() const;
+
void setNameFilterDetailsVisible(bool enabled);
bool isNameFilterDetailsVisible() const;
@@ -184,6 +191,12 @@ Q_SIGNALS:
void filesSelected(const QStringList &files);
void currentChanged(const QString &path);
void directoryEntered(const QString &directory);
+
+ void urlSelected(const QUrl &url);
+ void urlsSelected(const QList<QUrl> &urls);
+ void currentUrlChanged(const QUrl &url);
+ void directoryUrlEntered(const QUrl &directory);
+
void filterSelected(const QString &filter);
public:
@@ -195,6 +208,14 @@ public:
QString *selectedFilter = 0,
Options options = 0);
+ static QUrl getOpenFileUrl(QWidget *parent = 0,
+ const QString &caption = QString(),
+ const QUrl &dir = QUrl(),
+ const QString &filter = QString(),
+ QString *selectedFilter = 0,
+ Options options = 0,
+ const QStringList &supportedSchemes = QStringList());
+
static QString getSaveFileName(QWidget *parent = 0,
const QString &caption = QString(),
const QString &dir = QString(),
@@ -202,11 +223,25 @@ public:
QString *selectedFilter = 0,
Options options = 0);
+ static QUrl getSaveFileUrl(QWidget *parent = 0,
+ const QString &caption = QString(),
+ const QUrl &dir = QUrl(),
+ const QString &filter = QString(),
+ QString *selectedFilter = 0,
+ Options options = 0,
+ const QStringList &supportedSchemes = QStringList());
+
static QString getExistingDirectory(QWidget *parent = 0,
const QString &caption = QString(),
const QString &dir = QString(),
Options options = ShowDirsOnly);
+ static QUrl getExistingDirectoryUrl(QWidget *parent = 0,
+ const QString &caption = QString(),
+ const QUrl &dir = QUrl(),
+ Options options = ShowDirsOnly,
+ const QStringList &supportedSchemes = QStringList());
+
static QStringList getOpenFileNames(QWidget *parent = 0,
const QString &caption = QString(),
const QString &dir = QString(),
@@ -214,6 +249,14 @@ public:
QString *selectedFilter = 0,
Options options = 0);
+ static QList<QUrl> getOpenFileUrls(QWidget *parent = 0,
+ const QString &caption = QString(),
+ const QUrl &dir = QUrl(),
+ const QString &filter = QString(),
+ QString *selectedFilter = 0,
+ Options options = 0,
+ const QStringList &supportedSchemes = QStringList());
+
protected:
QFileDialog(const QFileDialogArgs &args);
@@ -240,7 +283,10 @@ private:
Q_PRIVATE_SLOT(d_func(), void _q_updateOkButton())
Q_PRIVATE_SLOT(d_func(), void _q_currentChanged(const QModelIndex &index))
Q_PRIVATE_SLOT(d_func(), void _q_enterDirectory(const QModelIndex &index))
- Q_PRIVATE_SLOT(d_func(), void _q_nativeEnterDirectory(const QString&))
+ Q_PRIVATE_SLOT(d_func(), void _q_nativeFileSelected(const QUrl &))
+ Q_PRIVATE_SLOT(d_func(), void _q_nativeFilesSelected(const QList<QUrl> &))
+ Q_PRIVATE_SLOT(d_func(), void _q_nativeCurrentChanged(const QUrl &))
+ Q_PRIVATE_SLOT(d_func(), void _q_nativeEnterDirectory(const QUrl&))
Q_PRIVATE_SLOT(d_func(), void _q_goToDirectory(const QString &path))
Q_PRIVATE_SLOT(d_func(), void _q_useNameFilter(int index))
Q_PRIVATE_SLOT(d_func(), void _q_selectionChanged())
diff --git a/src/widgets/dialogs/qfiledialog_p.h b/src/widgets/dialogs/qfiledialog_p.h
index f8f33eb18d..e5a558bb91 100644
--- a/src/widgets/dialogs/qfiledialog_p.h
+++ b/src/widgets/dialogs/qfiledialog_p.h
@@ -130,8 +130,9 @@ public:
static QString workingDirectory(const QString &path);
static QString initialSelection(const QString &path);
QStringList typedFiles() const;
- QStringList userSelectedFiles() const;
+ QList<QUrl> userSelectedFiles() const;
QStringList addDefaultSuffixToFiles(const QStringList filesToFix) const;
+ QList<QUrl> addDefaultSuffixToUrls(const QList<QUrl> &urlsToFix) const;
bool removeDirectory(const QString &path);
void setLabelTextControl(QFileDialog::DialogLabel label, const QString &text);
inline void updateFileNameLabel();
@@ -206,7 +207,10 @@ public:
void _q_updateOkButton();
void _q_currentChanged(const QModelIndex &index);
void _q_enterDirectory(const QModelIndex &index);
- void _q_nativeEnterDirectory(const QString &directory);
+ void _q_nativeFileSelected(const QUrl &file);
+ void _q_nativeFilesSelected(const QList<QUrl> &files);
+ void _q_nativeCurrentChanged(const QUrl &file);
+ void _q_nativeEnterDirectory(const QUrl &directory);
void _q_goToDirectory(const QString &);
void _q_useNameFilter(int index);
void _q_selectionChanged();
@@ -246,10 +250,10 @@ public:
// used instead.
bool canBeNativeDialog();
- void setDirectory_sys(const QString &directory);
- QString directory_sys() const;
- void selectFile_sys(const QString &filename);
- QStringList selectedFiles_sys() const;
+ void setDirectory_sys(const QUrl &directory);
+ QUrl directory_sys() const;
+ void selectFile_sys(const QUrl &filename);
+ QList<QUrl> selectedFiles_sys() const;
void setFilter_sys();
void selectNameFilter_sys(const QString &filter);
QString selectedNameFilter_sys() const;
@@ -346,30 +350,40 @@ inline QString QFileDialogPrivate::rootPath() const {
return model->rootPath();
}
-inline void QFileDialogPrivate::setDirectory_sys(const QString &directory)
+inline void QFileDialogPrivate::setDirectory_sys(const QUrl &directory)
{
- if (QPlatformFileDialogHelper *helper = platformFileDialogHelper())
+ QPlatformFileDialogHelper *helper = platformFileDialogHelper();
+
+ if (!helper)
+ return;
+
+ if (helper->isSupportedUrl(directory))
helper->setDirectory(directory);
}
-inline QString QFileDialogPrivate::directory_sys() const
+inline QUrl QFileDialogPrivate::directory_sys() const
{
if (QPlatformFileDialogHelper *helper = platformFileDialogHelper())
return helper->directory();
return QString();
}
-inline void QFileDialogPrivate::selectFile_sys(const QString &filename)
+inline void QFileDialogPrivate::selectFile_sys(const QUrl &filename)
{
- if (QPlatformFileDialogHelper *helper = platformFileDialogHelper())
+ QPlatformFileDialogHelper *helper = platformFileDialogHelper();
+
+ if (!helper)
+ return;
+
+ if (helper->isSupportedUrl(filename))
helper->selectFile(filename);
}
-inline QStringList QFileDialogPrivate::selectedFiles_sys() const
+inline QList<QUrl> QFileDialogPrivate::selectedFiles_sys() const
{
if (QPlatformFileDialogHelper *helper = platformFileDialogHelper())
return helper->selectedFiles();
- return QStringList();
+ return QList<QUrl>();
}
inline void QFileDialogPrivate::setFilter_sys()
diff --git a/src/widgets/dialogs/qfileinfogatherer.cpp b/src/widgets/dialogs/qfileinfogatherer.cpp
index 213aefe5f5..0f12c2b80e 100644
--- a/src/widgets/dialogs/qfileinfogatherer.cpp
+++ b/src/widgets/dialogs/qfileinfogatherer.cpp
@@ -238,7 +238,7 @@ QExtendedInformation QFileInfoGatherer::getInfo(const QFileInfo &fileInfo) const
#endif
#ifdef Q_OS_WIN
- if (m_resolveSymlinks && fileInfo.isSymLink()) {
+ if (m_resolveSymlinks && info.isSymLink(/* ignoreNtfsSymLinks = */ true)) {
QFileInfo resolvedInfo(fileInfo.symLinkTarget());
resolvedInfo = resolvedInfo.canonicalFilePath();
if (resolvedInfo.exists()) {
diff --git a/src/widgets/dialogs/qfileinfogatherer_p.h b/src/widgets/dialogs/qfileinfogatherer_p.h
index 0c4e644e40..447ee78edc 100644
--- a/src/widgets/dialogs/qfileinfogatherer_p.h
+++ b/src/widgets/dialogs/qfileinfogatherer_p.h
@@ -108,7 +108,13 @@ public:
return QExtendedInformation::System;
}
- bool isSymLink() const {
+ bool isSymLink(bool ignoreNtfsSymLinks = false) const
+ {
+ if (ignoreNtfsSymLinks) {
+#ifdef Q_OS_WIN
+ return !mFileInfo.suffix().compare(QLatin1String("lnk"), Qt::CaseInsensitive);
+#endif
+ }
return mFileInfo.isSymLink();
}
diff --git a/src/widgets/dialogs/qfilesystemmodel.cpp b/src/widgets/dialogs/qfilesystemmodel.cpp
index 8e3ecc3e0e..519c158f81 100644
--- a/src/widgets/dialogs/qfilesystemmodel.cpp
+++ b/src/widgets/dialogs/qfilesystemmodel.cpp
@@ -800,7 +800,7 @@ QString QFileSystemModelPrivate::name(const QModelIndex &index) const
if (!index.isValid())
return QString();
QFileSystemNode *dirNode = node(index);
- if (fileInfoGatherer.resolveSymlinks() && !resolvedSymLinks.isEmpty() && dirNode->isSymLink()) {
+ if (fileInfoGatherer.resolveSymlinks() && !resolvedSymLinks.isEmpty() && dirNode->isSymLink(/* ignoreNtfsSymLinks = */ true)) {
QString fullPath = QDir::fromNativeSeparators(filePath(index));
if (resolvedSymLinks.contains(fullPath))
return resolvedSymLinks[fullPath];
diff --git a/src/widgets/dialogs/qfilesystemmodel_p.h b/src/widgets/dialogs/qfilesystemmodel_p.h
index d61936d545..663be3d933 100644
--- a/src/widgets/dialogs/qfilesystemmodel_p.h
+++ b/src/widgets/dialogs/qfilesystemmodel_p.h
@@ -116,7 +116,7 @@ public:
inline bool isFile() const { if (info) return info->isFile(); return true; }
inline bool isSystem() const { if (info) return info->isSystem(); return true; }
inline bool isHidden() const { if (info) return info->isHidden(); return false; }
- inline bool isSymLink() const { if (info) return info->isSymLink(); return false; }
+ inline bool isSymLink(bool ignoreNtfsSymLinks = false) const { return info && info->isSymLink(ignoreNtfsSymLinks); }
inline bool caseSensitive() const { if (info) return info->isCaseSensitive(); return false; }
inline QIcon icon() const { if (info) return info->icon; return QIcon(); }
diff --git a/src/widgets/dialogs/qfontdialog.cpp b/src/widgets/dialogs/qfontdialog.cpp
index 313b475f1f..b989ea7c86 100644
--- a/src/widgets/dialogs/qfontdialog.cpp
+++ b/src/widgets/dialogs/qfontdialog.cpp
@@ -479,7 +479,22 @@ void QFontDialogPrivate::updateFamilies()
enum match_t { MATCH_NONE = 0, MATCH_LAST_RESORT = 1, MATCH_APP = 2, MATCH_FAMILY = 3 };
- QStringList familyNames = fdb.families(writingSystem);
+ const QFontDialog::FontDialogOptions scalableMask = (QFontDialog::ScalableFonts | QFontDialog::NonScalableFonts);
+ const QFontDialog::FontDialogOptions spacingMask = (QFontDialog::ProportionalFonts | QFontDialog::MonospacedFonts);
+ const QFontDialog::FontDialogOptions options = q->options();
+
+ QStringList familyNames;
+ foreach (const QString &family, fdb.families(writingSystem)) {
+ if ((options & scalableMask) && (options & scalableMask) != scalableMask) {
+ if (bool(options & QFontDialog::ScalableFonts) != fdb.isSmoothlyScalable(family))
+ continue;
+ }
+ if ((options & spacingMask) && (options & spacingMask) != spacingMask) {
+ if (bool(options & QFontDialog::MonospacedFonts) != fdb.isFixedPitch(family))
+ continue;
+ }
+ familyNames << family;
+ }
familyList->model()->setStringList(familyNames);
@@ -837,10 +852,21 @@ QFont QFontDialog::selectedFont() const
This enum specifies various options that affect the look and feel
of a font dialog.
+ For instance, it allows to specify which type of font should be
+ displayed. If none are specified all fonts available will be listed.
+
+ Note that the font filtering options might not be supported on some
+ platforms (e.g. Mac). They are always supported by the non native
+ dialog (used on Windows or Linux).
+
\value NoButtons Don't display \uicontrol{OK} and \uicontrol{Cancel} buttons. (Useful for "live dialogs".)
\value DontUseNativeDialog Use Qt's standard font dialog on the Mac instead of Apple's
native font panel. (Currently, the native dialog is never used,
but this is likely to change in future Qt releases.)
+ \value ScalableFonts Show scalable fonts
+ \value NonScalableFonts Show non scalable fonts
+ \value MonospacedFonts Show monospaced fonts
+ \value ProportionalFonts Show proportional fonts
\sa options, setOption(), testOption()
*/
diff --git a/src/widgets/dialogs/qfontdialog.h b/src/widgets/dialogs/qfontdialog.h
index c2d930bc1e..9956987cfe 100644
--- a/src/widgets/dialogs/qfontdialog.h
+++ b/src/widgets/dialogs/qfontdialog.h
@@ -64,7 +64,11 @@ class Q_WIDGETS_EXPORT QFontDialog : public QDialog
public:
enum FontDialogOption {
NoButtons = 0x00000001,
- DontUseNativeDialog = 0x00000002
+ DontUseNativeDialog = 0x00000002,
+ ScalableFonts = 0x00000004,
+ NonScalableFonts = 0x00000008,
+ MonospacedFonts = 0x00000010,
+ ProportionalFonts = 0x00000020
};
Q_DECLARE_FLAGS(FontDialogOptions, FontDialogOption)
diff --git a/src/widgets/dialogs/qinputdialog.cpp b/src/widgets/dialogs/qinputdialog.cpp
index 45aa49d552..c1f8deb4eb 100644
--- a/src/widgets/dialogs/qinputdialog.cpp
+++ b/src/widgets/dialogs/qinputdialog.cpp
@@ -49,6 +49,7 @@
#include "qlabel.h"
#include "qlayout.h"
#include "qlineedit.h"
+#include "qplaintextedit.h"
#include "qlistwidget.h"
#include "qpushbutton.h"
#include "qspinbox.h"
@@ -167,6 +168,7 @@ public:
void ensureLayout();
void ensureLineEdit();
+ void ensurePlainTextEdit();
void ensureComboBox();
void ensureListView();
void ensureIntSpinBox();
@@ -180,11 +182,13 @@ public:
void ensureLayout() const { const_cast<QInputDialogPrivate *>(this)->ensureLayout(); }
bool useComboBoxOrListView() const { return comboBox && comboBox->count() > 0; }
void _q_textChanged(const QString &text);
+ void _q_plainTextEditTextChanged();
void _q_currentRowChanged(const QModelIndex &newIndex, const QModelIndex &oldIndex);
mutable QLabel *label;
mutable QDialogButtonBox *buttonBox;
mutable QLineEdit *lineEdit;
+ mutable QPlainTextEdit *plainTextEdit;
mutable QSpinBox *intSpinBox;
mutable QDoubleSpinBox *doubleSpinBox;
mutable QComboBox *comboBox;
@@ -198,8 +202,8 @@ public:
};
QInputDialogPrivate::QInputDialogPrivate()
- : label(0), buttonBox(0), lineEdit(0), intSpinBox(0), doubleSpinBox(0), comboBox(0), listView(0),
- inputWidget(0), mainLayout(0)
+ : label(0), buttonBox(0), lineEdit(0), plainTextEdit(0), intSpinBox(0), doubleSpinBox(0),
+ comboBox(0), listView(0), inputWidget(0), mainLayout(0)
{
}
@@ -250,6 +254,21 @@ void QInputDialogPrivate::ensureLineEdit()
}
}
+void QInputDialogPrivate::ensurePlainTextEdit()
+{
+ Q_Q(QInputDialog);
+ if (!plainTextEdit) {
+ plainTextEdit = new QPlainTextEdit(q);
+ plainTextEdit->setLineWrapMode(QPlainTextEdit::NoWrap);
+#ifndef QT_NO_IM
+ qt_widget_private(plainTextEdit)->inheritsInputMethodHints = 1;
+#endif
+ plainTextEdit->hide();
+ QObject::connect(plainTextEdit, SIGNAL(textChanged()),
+ q, SLOT(_q_plainTextEditTextChanged()));
+ }
+}
+
void QInputDialogPrivate::ensureComboBox()
{
Q_Q(QInputDialog);
@@ -344,6 +363,8 @@ void QInputDialogPrivate::setInputWidget(QWidget *widget)
// textValue
if (widget == lineEdit) {
lineEdit->setText(textValue);
+ } else if (widget == plainTextEdit) {
+ plainTextEdit->setPlainText(textValue);
} else if (widget == comboBox) {
setComboBoxText(textValue);
} else if (widget == listView) {
@@ -364,6 +385,9 @@ void QInputDialogPrivate::chooseRightTextInputWidget()
} else {
widget = comboBox;
}
+ } else if (opts & QInputDialog::UsePlainTextEditForTextInput) {
+ ensurePlainTextEdit();
+ widget = plainTextEdit;
} else {
ensureLineEdit();
widget = lineEdit;
@@ -417,6 +441,16 @@ void QInputDialogPrivate::_q_textChanged(const QString &text)
}
}
+void QInputDialogPrivate::_q_plainTextEditTextChanged()
+{
+ Q_Q(QInputDialog);
+ QString text = plainTextEdit->toPlainText();
+ if (textValue != text) {
+ textValue = text;
+ emit q->textValueChanged(text);
+ }
+}
+
void QInputDialogPrivate::_q_currentRowChanged(const QModelIndex &newIndex,
const QModelIndex & /* oldIndex */)
{
@@ -434,8 +468,8 @@ void QInputDialogPrivate::_q_currentRowChanged(const QModelIndex &newIndex,
The input value can be a string, a number or an item from a list. A label
must be set to tell the user what they should enter.
- Four static convenience functions are provided: getText(), getInt(),
- getDouble(), and getItem(). All the functions can be used in a similar way,
+ Five static convenience functions are provided: getText(), getMultiLineText(),
+ getInt(), getDouble(), and getItem(). All the functions can be used in a similar way,
for example:
\snippet dialogs/standarddialogs/dialog.cpp 3
@@ -575,6 +609,8 @@ QString QInputDialog::labelText() const
\value NoButtons Don't display \uicontrol{OK} and \uicontrol{Cancel} buttons (useful for "live dialogs").
\value UseListViewForComboBoxItems Use a QListView rather than a non-editable QComboBox for
displaying the items set with setComboBoxItems().
+ \value UsePlainTextEditForTextInput Use a QPlainTextEdit for multiline text input. This value was
+ introduced in 5.2.
\sa options, setOption(), testOption()
*/
@@ -628,6 +664,8 @@ void QInputDialog::setOptions(InputDialogOptions options)
d->buttonBox->setVisible(!(options & NoButtons));
if ((changed & UseListViewForComboBoxItems) && inputMode() == TextInput)
d->chooseRightTextInputWidget();
+ if ((changed & UsePlainTextEditForTextInput) && inputMode() == TextInput)
+ d->chooseRightTextInputWidget();
}
QInputDialog::InputDialogOptions QInputDialog::options() const
@@ -653,6 +691,8 @@ void QInputDialog::setTextValue(const QString &text)
setInputMode(TextInput);
if (d->inputWidget == d->lineEdit) {
d->lineEdit->setText(text);
+ } else if (d->inputWidget == d->plainTextEdit) {
+ d->plainTextEdit->setPlainText(text);
} else if (d->inputWidget == d->comboBox) {
d->setComboBoxText(text);
} else {
@@ -1075,6 +1115,8 @@ void QInputDialog::setVisible(bool visible)
d->inputWidget->setFocus();
if (d->inputWidget == d->lineEdit) {
d->lineEdit->selectAll();
+ } else if (d->inputWidget == d->plainTextEdit) {
+ d->plainTextEdit->selectAll();
} else if (d->inputWidget == d->intSpinBox) {
d->intSpinBox->selectAll();
} else if (d->inputWidget == d->doubleSpinBox) {
@@ -1144,7 +1186,7 @@ void QInputDialog::done(int result)
want to do this, you should create the dialog yourself using one of the
QInputDialog constructors.
- \sa getInt(), getDouble(), getItem()
+ \sa getInt(), getDouble(), getItem(), getMultiLineText()
*/
QString QInputDialog::getText(QWidget *parent, const QString &title, const QString &label,
@@ -1169,6 +1211,58 @@ QString QInputDialog::getText(QWidget *parent, const QString &title, const QStri
}
/*!
+ \since 5.2
+
+ Static convenience function to get a multiline string from the user.
+
+ \a title is the text which is displayed in the title bar of the dialog.
+ \a label is the text which is shown to the user (it should say what should
+ be entered).
+ \a text is the default text which is placed in the plain text edit.
+ \a inputMethodHints is the input method hints that will be used in the
+ edit widget if an input method is active.
+
+ If \a ok is nonnull \e *\a ok will be set to true if the user pressed
+ \uicontrol OK and to false if the user pressed \uicontrol Cancel. The dialog's parent
+ is \a parent. The dialog will be modal and uses the specified widget
+ \a flags.
+
+ If the dialog is accepted, this function returns the text in the dialog's
+ plain text edit. If the dialog is rejected, a null QString is returned.
+
+ Use this static function like this:
+
+ \snippet dialogs/standarddialogs/dialog.cpp 4
+
+ \warning Do not delete \a parent during the execution of the dialog. If you
+ want to do this, you should create the dialog yourself using one of the
+ QInputDialog constructors.
+
+ \sa getInt(), getDouble(), getItem(), getText()
+*/
+
+QString QInputDialog::getMultiLineText(QWidget *parent, const QString &title, const QString &label,
+ const QString &text, bool *ok, Qt::WindowFlags flags,
+ Qt::InputMethodHints inputMethodHints)
+{
+ QInputDialog dialog(parent, flags);
+ dialog.setOptions(QInputDialog::UsePlainTextEditForTextInput);
+ dialog.setWindowTitle(title);
+ dialog.setLabelText(label);
+ dialog.setTextValue(text);
+ dialog.setInputMethodHints(inputMethodHints);
+
+ int ret = dialog.exec();
+ if (ok)
+ *ok = !!ret;
+ if (ret) {
+ return dialog.textValue();
+ } else {
+ return QString();
+ }
+}
+
+/*!
\since 4.5
Static convenience function to get an integer input from the user.
@@ -1196,7 +1290,7 @@ QString QInputDialog::getText(QWidget *parent, const QString &title, const QStri
want to do this, you should create the dialog yourself using one of the
QInputDialog constructors.
- \sa getText(), getDouble(), getItem()
+ \sa getText(), getDouble(), getItem(), getMultiLineText()
*/
int QInputDialog::getInt(QWidget *parent, const QString &title, const QString &label, int value,
@@ -1248,7 +1342,7 @@ int QInputDialog::getInt(QWidget *parent, const QString &title, const QString &l
want to do this, you should create the dialog yourself using one of the
QInputDialog constructors.
- \sa getText(), getDouble(), getItem()
+ \sa getText(), getDouble(), getItem(), getMultiLineText()
*/
/*!
@@ -1277,7 +1371,7 @@ int QInputDialog::getInt(QWidget *parent, const QString &title, const QString &l
want to do this, you should create the dialog yourself using one of the
QInputDialog constructors.
- \sa getText(), getInt(), getItem()
+ \sa getText(), getInt(), getItem(), getMultiLineText()
*/
double QInputDialog::getDouble(QWidget *parent, const QString &title, const QString &label,
@@ -1331,7 +1425,7 @@ double QInputDialog::getDouble(QWidget *parent, const QString &title, const QStr
want to do this, you should create the dialog yourself using one of the
QInputDialog constructors.
- \sa getText(), getInt(), getDouble()
+ \sa getText(), getInt(), getDouble(), getMultiLineText()
*/
QString QInputDialog::getItem(QWidget *parent, const QString &title, const QString &label,
diff --git a/src/widgets/dialogs/qinputdialog.h b/src/widgets/dialogs/qinputdialog.h
index 41dca1f94f..c2c85835c8 100644
--- a/src/widgets/dialogs/qinputdialog.h
+++ b/src/widgets/dialogs/qinputdialog.h
@@ -78,8 +78,9 @@ class Q_WIDGETS_EXPORT QInputDialog : public QDialog
public:
enum InputDialogOption {
- NoButtons = 0x00000001,
- UseListViewForComboBoxItems = 0x00000002
+ NoButtons = 0x00000001,
+ UseListViewForComboBoxItems = 0x00000002,
+ UsePlainTextEditForTextInput = 0x00000004
};
Q_DECLARE_FLAGS(InputDialogOptions, InputDialogOption)
@@ -168,6 +169,9 @@ public:
QLineEdit::EchoMode echo = QLineEdit::Normal,
const QString &text = QString(), bool *ok = 0, Qt::WindowFlags flags = 0,
Qt::InputMethodHints inputMethodHints = Qt::ImhNone);
+ static QString getMultiLineText(QWidget *parent, const QString &title, const QString &label,
+ const QString &text = QString(), bool *ok = 0, Qt::WindowFlags flags = 0,
+ Qt::InputMethodHints inputMethodHints = Qt::ImhNone);
static QString getItem(QWidget *parent, const QString &title, const QString &label,
const QStringList &items, int current = 0, bool editable = true,
bool *ok = 0, Qt::WindowFlags flags = 0,
@@ -204,6 +208,7 @@ public:
private:
Q_DISABLE_COPY(QInputDialog)
Q_PRIVATE_SLOT(d_func(), void _q_textChanged(const QString&))
+ Q_PRIVATE_SLOT(d_func(), void _q_plainTextEditTextChanged())
Q_PRIVATE_SLOT(d_func(), void _q_currentRowChanged(const QModelIndex&, const QModelIndex&))
};
diff --git a/src/widgets/dialogs/qmessagebox.cpp b/src/widgets/dialogs/qmessagebox.cpp
index 995d279e13..e51143cb7e 100644
--- a/src/widgets/dialogs/qmessagebox.cpp
+++ b/src/widgets/dialogs/qmessagebox.cpp
@@ -201,6 +201,7 @@ public:
detectedEscapeButton(0), informativeLabel(0) { }
void init(const QString &title = QString(), const QString &text = QString());
+ void setupLayout();
void _q_buttonClicked(QAbstractButton *);
QAbstractButton *findButton(int button0, int button1, int button2, int flags);
@@ -271,7 +272,6 @@ void QMessageBoxPrivate::init(const QString &title, const QString &text)
label->setContentsMargins(2, 0, 0, 0);
label->setIndent(9);
#endif
- icon = QMessageBox::NoIcon;
iconLabel = new QLabel;
iconLabel->setObjectName(QLatin1String("qt_msgboxex_icon_label"));
iconLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
@@ -281,41 +281,50 @@ void QMessageBoxPrivate::init(const QString &title, const QString &text)
buttonBox->setCenterButtons(q->style()->styleHint(QStyle::SH_MessageBox_CenterButtons, 0, q));
QObject::connect(buttonBox, SIGNAL(clicked(QAbstractButton*)),
q, SLOT(_q_buttonClicked(QAbstractButton*)));
+ setupLayout();
+ if (!title.isEmpty() || !text.isEmpty()) {
+ q->setWindowTitle(title);
+ q->setText(text);
+ }
+ q->setModal(true);
+#ifdef Q_OS_MAC
+ QFont f = q->font();
+ f.setBold(true);
+ label->setFont(f);
+#endif
+ icon = QMessageBox::NoIcon;
+}
+void QMessageBoxPrivate::setupLayout()
+{
+ Q_Q(QMessageBox);
+ delete q->layout();
QGridLayout *grid = new QGridLayout;
-#ifndef Q_OS_MAC
grid->addWidget(iconLabel, 0, 0, 2, 1, Qt::AlignTop);
grid->addWidget(label, 0, 1, 1, 1);
- // -- leave space for information label --
+ if (informativeLabel)
+ grid->addWidget(informativeLabel, 1, 1, 1, 1);
+#ifndef Q_OS_MAC
grid->addWidget(buttonBox, 2, 0, 1, 2);
#else
+ grid->addWidget(buttonBox, 3, 1, 1, 1);
+#endif
+ if (detailsText)
+ grid->addWidget(detailsText, grid->rowCount(), 0, 1, grid->columnCount());
+#ifdef Q_OS_MAC
grid->setMargin(0);
grid->setVerticalSpacing(8);
grid->setHorizontalSpacing(0);
q->setContentsMargins(24, 15, 24, 20);
- grid->addWidget(iconLabel, 0, 0, 2, 1, Qt::AlignTop | Qt::AlignLeft);
- grid->addWidget(label, 0, 1, 1, 1);
- // -- leave space for information label --
grid->setRowStretch(1, 100);
grid->setRowMinimumHeight(2, 6);
- grid->addWidget(buttonBox, 3, 1, 1, 1);
#endif
grid->setSizeConstraint(QLayout::SetNoConstraint);
q->setLayout(grid);
- if (!title.isEmpty() || !text.isEmpty()) {
- q->setWindowTitle(title);
- q->setText(text);
- }
- q->setModal(true);
-
-#ifdef Q_OS_MAC
- QFont f = q->font();
- f.setBold(true);
- label->setFont(f);
-#endif
retranslateStrings();
+ updateSize();
}
int QMessageBoxPrivate::layoutMinimumWidth()
@@ -2458,24 +2467,27 @@ void QMessageBox::setDetailedText(const QString &text)
{
Q_D(QMessageBox);
if (text.isEmpty()) {
- delete d->detailsText;
+ if (d->detailsText) {
+ d->detailsText->hide();
+ d->detailsText->deleteLater();
+ }
d->detailsText = 0;
removeButton(d->detailsButton);
- delete d->detailsButton;
+ if (d->detailsButton) {
+ d->detailsButton->hide();
+ d->detailsButton->deleteLater();
+ }
d->detailsButton = 0;
- return;
- }
-
- if (!d->detailsText) {
- d->detailsText = new QMessageBoxDetailsText(this);
- QGridLayout* grid = qobject_cast<QGridLayout*>(layout());
- if (grid)
- grid->addWidget(d->detailsText, grid->rowCount(), 0, 1, grid->columnCount());
- d->detailsText->hide();
+ } else {
+ if (!d->detailsText) {
+ d->detailsText = new QMessageBoxDetailsText(this);
+ d->detailsText->hide();
+ }
+ if (!d->detailsButton)
+ d->detailsButton = new DetailButton(this);
+ d->detailsText->setText(text);
}
- if (!d->detailsButton)
- d->detailsButton = new DetailButton(this);
- d->detailsText->setText(text);
+ d->setupLayout();
}
#endif // QT_NO_TEXTEDIT
@@ -2506,39 +2518,37 @@ void QMessageBox::setInformativeText(const QString &text)
{
Q_D(QMessageBox);
if (text.isEmpty()) {
- layout()->removeWidget(d->informativeLabel);
- delete d->informativeLabel;
+ if (d->informativeLabel) {
+ d->informativeLabel->hide();
+ d->informativeLabel->deleteLater();
+ }
d->informativeLabel = 0;
#ifndef Q_OS_MAC
d->label->setContentsMargins(2, 0, 0, 0);
#endif
- d->updateSize();
- return;
- }
-
- if (!d->informativeLabel) {
- QLabel *label = new QLabel;
- label->setObjectName(QLatin1String("qt_msgbox_informativelabel"));
- label->setTextInteractionFlags(Qt::TextInteractionFlags(style()->styleHint(QStyle::SH_MessageBox_TextInteractionFlags, 0, this)));
- label->setAlignment(Qt::AlignTop | Qt::AlignLeft);
- label->setOpenExternalLinks(true);
- label->setWordWrap(true);
+ } else {
+ if (!d->informativeLabel) {
+ QLabel *label = new QLabel;
+ label->setObjectName(QLatin1String("qt_msgbox_informativelabel"));
+ label->setTextInteractionFlags(Qt::TextInteractionFlags(style()->styleHint(QStyle::SH_MessageBox_TextInteractionFlags, 0, this)));
+ label->setAlignment(Qt::AlignTop | Qt::AlignLeft);
+ label->setOpenExternalLinks(true);
+ label->setWordWrap(true);
#ifndef Q_OS_MAC
- d->label->setContentsMargins(2, 0, 0, 0);
- label->setContentsMargins(2, 0, 0, 6);
- label->setIndent(9);
+ d->label->setContentsMargins(2, 0, 0, 0);
+ label->setContentsMargins(2, 0, 0, 6);
+ label->setIndent(9);
#else
- label->setContentsMargins(16, 0, 0, 0);
- // apply a smaller font the information label on the mac
- label->setFont(qt_app_fonts_hash()->value("QTipLabel"));
+ label->setContentsMargins(16, 0, 0, 0);
+ // apply a smaller font the information label on the mac
+ label->setFont(qt_app_fonts_hash()->value("QTipLabel"));
#endif
- label->setWordWrap(true);
- QGridLayout *grid = static_cast<QGridLayout *>(layout());
- grid->addWidget(label, 1, 1, 1, 1);
- d->informativeLabel = label;
+ label->setWordWrap(true);
+ d->informativeLabel = label;
+ }
+ d->informativeLabel->setText(text);
}
- d->informativeLabel->setText(text);
- d->updateSize();
+ d->setupLayout();
}
/*!
diff --git a/src/widgets/doc/qtwidgets.qdocconf b/src/widgets/doc/qtwidgets.qdocconf
index a989ef9363..d3c7825bc0 100644
--- a/src/widgets/doc/qtwidgets.qdocconf
+++ b/src/widgets/doc/qtwidgets.qdocconf
@@ -54,3 +54,6 @@ imagedirs += images \
../../../doc/src/images \
../../../examples/widgets/doc/images \
../../../examples/widgets
+
+navigation.landingpage = "Qt Widgets"
+navigation.cppclassespage = "Qt Widgets C++ Classes"
diff --git a/src/widgets/doc/src/qtwidgets-examples.qdoc b/src/widgets/doc/src/qtwidgets-examples.qdoc
index 7111eb81b0..985aa24749 100644
--- a/src/widgets/doc/src/qtwidgets-examples.qdoc
+++ b/src/widgets/doc/src/qtwidgets-examples.qdoc
@@ -112,7 +112,7 @@
/*!
\ingroup all-examples
- \title Itemview Examples
+ \title Item Views Examples
\brief Using the model/view framework.
\group examples-itemviews
diff --git a/src/widgets/doc/src/qtwidgets.qdoc b/src/widgets/doc/src/qtwidgets.qdoc
index 2e3403e9d9..e6145ea17e 100644
--- a/src/widgets/doc/src/qtwidgets.qdoc
+++ b/src/widgets/doc/src/qtwidgets.qdoc
@@ -29,6 +29,7 @@
\module QtWidgets
\title Qt Widgets C++ Classes
\ingroup modules
+ \qtvariable widgets
\brief The Qt Widgets module extends Qt GUI with C++ widget functionality.
diff --git a/src/widgets/graphicsview/qgridlayoutengine.cpp b/src/widgets/graphicsview/qgridlayoutengine.cpp
index 4f43a0a4ac..f741962264 100644
--- a/src/widgets/graphicsview/qgridlayoutengine.cpp
+++ b/src/widgets/graphicsview/qgridlayoutengine.cpp
@@ -432,6 +432,8 @@ QGridLayoutBox QGridLayoutRowData::totalBox(int start, int end) const
result.q_maximumSize = 0.0;
qreal nextSpacing = 0.0;
for (int i = start; i < end; ++i) {
+ if (ignore.testBit(i))
+ continue;
result.add(boxes.at(i), stretches.at(i), nextSpacing);
nextSpacing = spacings.at(i);
}
@@ -1475,7 +1477,7 @@ void QGridLayoutEngine::fillRowData(QGridLayoutRowData *rowData, const QLayoutSt
int effectiveRowSpan = 1;
for (int i = 1; i < itemRowSpan; ++i) {
- if (!rowData->ignore.testBit(i))
+ if (!rowData->ignore.testBit(i + itemRow))
++effectiveRowSpan;
}
@@ -1713,7 +1715,8 @@ void QGridLayoutEngine::ensureGeometries(const QLayoutStyleInfo &styleInfo,
q_descents.resize(rowCount());
if (constraintOrientation() != Qt::Horizontal) {
- //We might have items whose width depends on their height
+ // We might have items whose height depends on their width,
+ // or none of the items has a dynamic constraint.
ensureColumnAndRowData(&q_columnData, &q_totalBoxes[Hor], styleInfo, NULL, NULL, Qt::Horizontal);
//Calculate column widths and positions, and put results in q_xx.data() and q_widths.data() so that we can use this information as
//constraints to find the row heights
@@ -1724,7 +1727,7 @@ void QGridLayoutEngine::ensureGeometries(const QLayoutStyleInfo &styleInfo,
q_rowData.calculateGeometries(0, rowCount(), size.height(), q_yy.data(), q_heights.data(),
q_descents.data(), q_totalBoxes[Ver], q_infos[Ver]);
} else {
- //We have items whose height depends on their width
+ // We have items whose width depends on their height
ensureColumnAndRowData(&q_rowData, &q_totalBoxes[Ver], styleInfo, NULL, NULL, Qt::Vertical);
//Calculate row heights and positions, and put results in q_yy.data() and q_heights.data() so that we can use this information as
//constraints to find the column widths
diff --git a/src/widgets/itemviews/itemviews.pri b/src/widgets/itemviews/itemviews.pri
index 0bc0309271..4e152d18bb 100644
--- a/src/widgets/itemviews/itemviews.pri
+++ b/src/widgets/itemviews/itemviews.pri
@@ -26,6 +26,7 @@ HEADERS += \
itemviews/qtreewidgetitemiterator.h \
itemviews/qdatawidgetmapper.h \
itemviews/qfileiconprovider.h \
+ itemviews/qfileiconprovider_p.h \
itemviews/qcolumnviewgrip_p.h \
itemviews/qcolumnview.h \
itemviews/qcolumnview_p.h \
diff --git a/src/widgets/itemviews/qabstractitemview.cpp b/src/widgets/itemviews/qabstractitemview.cpp
index 70c8f44a73..b79525b9df 100644
--- a/src/widgets/itemviews/qabstractitemview.cpp
+++ b/src/widgets/itemviews/qabstractitemview.cpp
@@ -1108,6 +1108,7 @@ void QAbstractItemView::reset()
QAccessible::updateAccessibility(&accessibleEvent);
}
#endif
+ d->updateGeometry();
}
/*!
@@ -1124,6 +1125,7 @@ void QAbstractItemView::setRootIndex(const QModelIndex &index)
}
d->root = index;
d->doDelayedItemsLayout();
+ d->updateGeometry();
}
/*!
@@ -2668,8 +2670,10 @@ void QAbstractItemView::updateEditorGeometries()
*/
void QAbstractItemView::updateGeometries()
{
+ Q_D(QAbstractItemView);
updateEditorGeometries();
- d_func()->fetchMoreTimer.start(0, this); //fetch more later
+ d->fetchMoreTimer.start(0, this); //fetch more later
+ d->updateGeometry();
}
/*!
@@ -3231,6 +3235,7 @@ void QAbstractItemView::dataChanged(const QModelIndex &topLeft, const QModelInde
QAccessible::updateAccessibility(&accessibleEvent);
}
#endif
+ d->updateGeometry();
}
/*!
@@ -3332,6 +3337,7 @@ void QAbstractItemViewPrivate::_q_rowsRemoved(const QModelIndex &index, int star
QAccessible::updateAccessibility(&accessibleEvent);
}
#endif
+ updateGeometry();
}
/*!
@@ -3412,6 +3418,7 @@ void QAbstractItemViewPrivate::_q_columnsRemoved(const QModelIndex &index, int s
QAccessible::updateAccessibility(&accessibleEvent);
}
#endif
+ updateGeometry();
}
@@ -3435,6 +3442,7 @@ void QAbstractItemViewPrivate::_q_rowsInserted(const QModelIndex &index, int sta
QAccessible::updateAccessibility(&accessibleEvent);
}
#endif
+ updateGeometry();
}
/*!
@@ -3459,6 +3467,7 @@ void QAbstractItemViewPrivate::_q_columnsInserted(const QModelIndex &index, int
QAccessible::updateAccessibility(&accessibleEvent);
}
#endif
+ updateGeometry();
}
/*!
@@ -4084,7 +4093,14 @@ void QAbstractItemViewPrivate::interruptDelayedItemsLayout() const
delayedPendingLayout = false;
}
-
+void QAbstractItemViewPrivate::updateGeometry()
+{
+ Q_Q(QAbstractItemView);
+ if (sizeAdjustPolicy == QAbstractScrollArea::AdjustIgnored)
+ return;
+ if (sizeAdjustPolicy == QAbstractScrollArea::AdjustToContents || !shownOnce)
+ q->updateGeometry();
+}
QWidget *QAbstractItemViewPrivate::editor(const QModelIndex &index,
const QStyleOptionViewItem &options)
diff --git a/src/widgets/itemviews/qabstractitemview_p.h b/src/widgets/itemviews/qabstractitemview_p.h
index 86eab174ed..5da22615e2 100644
--- a/src/widgets/itemviews/qabstractitemview_p.h
+++ b/src/widgets/itemviews/qabstractitemview_p.h
@@ -127,6 +127,8 @@ public:
void doDelayedItemsLayout(int delay = 0);
void interruptDelayedItemsLayout() const;
+ void updateGeometry();
+
void startAutoScroll()
{ // ### it would be nice to make this into a style hint one day
int scrollInterval = (verticalScrollMode == QAbstractItemView::ScrollPerItem) ? 150 : 50;
diff --git a/src/widgets/itemviews/qcolumnview.cpp b/src/widgets/itemviews/qcolumnview.cpp
index 5aee78fab4..32a3dddca1 100644
--- a/src/widgets/itemviews/qcolumnview.cpp
+++ b/src/widgets/itemviews/qcolumnview.cpp
@@ -332,11 +332,14 @@ void QColumnView::scrollTo(const QModelIndex &index, ScrollHint hint)
}
#ifndef QT_NO_ANIMATION
- d->currentAnimation.setEndValue(newScrollbarValue);
- d->currentAnimation.start();
-#else
- horizontalScrollBar()->setValue(newScrollbarValue);
+ if (style()->styleHint(QStyle::SH_Widget_Animate, 0, this)) {
+ d->currentAnimation.setEndValue(newScrollbarValue);
+ d->currentAnimation.start();
+ } else
#endif //QT_NO_ANIMATION
+ {
+ horizontalScrollBar()->setValue(newScrollbarValue);
+ }
}
/*!
diff --git a/src/widgets/itemviews/qfileiconprovider.cpp b/src/widgets/itemviews/qfileiconprovider.cpp
index 8a0736ec70..71697ddc40 100644
--- a/src/widgets/itemviews/qfileiconprovider.cpp
+++ b/src/widgets/itemviews/qfileiconprovider.cpp
@@ -40,9 +40,8 @@
****************************************************************************/
#include "qfileiconprovider.h"
+#include "qfileiconprovider_p.h"
-#ifndef QT_NO_FILEICONPROVIDER
-#include <qstyle.h>
#include <qapplication.h>
#include <qdir.h>
#include <qpixmapcache.h>
@@ -83,34 +82,15 @@ QT_BEGIN_NAMESPACE
\value File
*/
-class QFileIconProviderPrivate
-{
- Q_DECLARE_PUBLIC(QFileIconProvider)
-
-public:
- QFileIconProviderPrivate();
- QIcon getIcon(QStyle::StandardPixmap name) const;
- QIcon getIcon(const QFileInfo &fi) const;
-
- QFileIconProvider *q_ptr;
- const QString homePath;
-
-private:
- mutable QIcon file;
- mutable QIcon fileLink;
- mutable QIcon directory;
- mutable QIcon directoryLink;
- mutable QIcon harddisk;
- mutable QIcon floppy;
- mutable QIcon cdrom;
- mutable QIcon ram;
- mutable QIcon network;
- mutable QIcon computer;
- mutable QIcon desktop;
- mutable QIcon trashcan;
- mutable QIcon generic;
- mutable QIcon home;
-};
+
+/*!
+ \enum QFileIconProvider::Option
+ \since 5.2
+
+ \value DontUseCustomDirectoryIcons Always use the default directory icon.
+ Some platforms allow the user to set a different icon. Custom icon lookup
+ cause a big performance impact over network or removable drives.
+*/
QFileIconProviderPrivate::QFileIconProviderPrivate() :
homePath(QDir::home().absolutePath())
@@ -193,6 +173,31 @@ QFileIconProvider::~QFileIconProvider()
}
/*!
+ \since 5.2
+ Sets \a options that affect the icon provider.
+ \sa options()
+*/
+
+void QFileIconProvider::setOptions(QFileIconProvider::Options options)
+{
+ Q_D(QFileIconProvider);
+ d->options = options;
+}
+
+/*!
+ \since 5.2
+ Returns all the options that affect the icon provider.
+ By default, all options are disabled.
+ \sa setOptions()
+*/
+
+QFileIconProvider::Options QFileIconProvider::options() const
+{
+ Q_D(const QFileIconProvider);
+ return d->options;
+}
+
+/*!
Returns an icon set for the given \a type.
*/
@@ -220,6 +225,23 @@ QIcon QFileIconProvider::icon(IconType type) const
return QIcon();
}
+static bool isCacheable(const QFileInfo &fi)
+{
+ if (!fi.isFile())
+ return false;
+
+#ifdef Q_OS_WIN
+ // On windows it's faster to just look at the file extensions. QTBUG-13182
+ const QString fileExtension = fi.suffix();
+ // Will return false for .exe, .lnk and .ico extensions
+ return fileExtension.compare(QLatin1String("exe"), Qt::CaseInsensitive) &&
+ fileExtension.compare(QLatin1String("lnk"), Qt::CaseInsensitive) &&
+ fileExtension.compare(QLatin1String("ico"), Qt::CaseInsensitive);
+#else
+ return !fi.isExecutable() && !fi.isSymLink();
+#endif
+}
+
QIcon QFileIconProviderPrivate::getIcon(const QFileInfo &fi) const
{
QIcon retIcon;
@@ -231,10 +253,9 @@ QIcon QFileIconProviderPrivate::getIcon(const QFileInfo &fi) const
if (sizes.isEmpty())
return retIcon;
- const QString fileExtension = fi.suffix().toUpper();
const QString keyBase = QLatin1String("qt_.") + fi.suffix().toUpper();
- bool cacheable = fi.isFile() && !fi.isExecutable() && !fi.isSymLink() && fileExtension != QLatin1String("ICO");
+ bool cacheable = isCacheable(fi);
if (cacheable) {
QPixmap pixmap;
QPixmapCache::find(keyBase + QString::number(sizes.at(0)), pixmap);
@@ -253,8 +274,12 @@ QIcon QFileIconProviderPrivate::getIcon(const QFileInfo &fi) const
}
}
+ QPlatformTheme::IconOptions iconOptions;
+ if (options & QFileIconProvider::DontUseCustomDirectoryIcons)
+ iconOptions |= QPlatformTheme::DontUseCustomDirectoryIcons;
+
Q_FOREACH (int size, sizes) {
- QPixmap pixmap = theme->fileIconPixmap(fi, QSizeF(size, size));
+ QPixmap pixmap = theme->fileIconPixmap(fi, QSizeF(size, size), iconOptions);
if (!pixmap.isNull()) {
retIcon.addPixmap(pixmap);
if (cacheable)
@@ -372,5 +397,3 @@ QString QFileIconProvider::type(const QFileInfo &info) const
}
QT_END_NAMESPACE
-
-#endif
diff --git a/src/widgets/itemviews/qfileiconprovider.h b/src/widgets/itemviews/qfileiconprovider.h
index cac135fe71..6f7e28395b 100644
--- a/src/widgets/itemviews/qfileiconprovider.h
+++ b/src/widgets/itemviews/qfileiconprovider.h
@@ -49,8 +49,6 @@
QT_BEGIN_NAMESPACE
-#ifndef QT_NO_FILEICONPROVIDER
-
class QFileIconProviderPrivate;
class Q_WIDGETS_EXPORT QFileIconProvider
@@ -59,19 +57,27 @@ public:
QFileIconProvider();
virtual ~QFileIconProvider();
enum IconType { Computer, Desktop, Trashcan, Network, Drive, Folder, File };
+
+ enum Option {
+ DontUseCustomDirectoryIcons = 0x00000001
+ };
+ Q_DECLARE_FLAGS(Options, Option)
+
virtual QIcon icon(IconType type) const;
virtual QIcon icon(const QFileInfo &info) const;
virtual QString type(const QFileInfo &info) const;
+ void setOptions(Options options);
+ Options options() const;
+
private:
Q_DECLARE_PRIVATE(QFileIconProvider)
QScopedPointer<QFileIconProviderPrivate> d_ptr;
Q_DISABLE_COPY(QFileIconProvider)
};
-#endif // QT_NO_FILEICONPROVIDER
+Q_DECLARE_OPERATORS_FOR_FLAGS(QFileIconProvider::Options)
QT_END_NAMESPACE
#endif // QFILEICONPROVIDER_H
-
diff --git a/src/widgets/itemviews/qfileiconprovider_p.h b/src/widgets/itemviews/qfileiconprovider_p.h
new file mode 100644
index 0000000000..9b2d536258
--- /dev/null
+++ b/src/widgets/itemviews/qfileiconprovider_p.h
@@ -0,0 +1,87 @@
+/****************************************************************************
+**
+** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
+** Contact: http://www.qt-project.org/legal
+**
+** This file is part of the QtWidgets module of the Qt Toolkit.
+**
+** $QT_BEGIN_LICENSE:LGPL$
+** Commercial License Usage
+** Licensees holding valid commercial Qt licenses may use this file in
+** accordance with the commercial license agreement provided with the
+** Software or, alternatively, in accordance with the terms contained in
+** a written agreement between you and Digia. For licensing terms and
+** conditions see http://qt.digia.com/licensing. For further information
+** use the contact form at http://qt.digia.com/contact-us.
+**
+** GNU Lesser General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU Lesser
+** General Public License version 2.1 as published by the Free Software
+** Foundation and appearing in the file LICENSE.LGPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU Lesser General Public License version 2.1 requirements
+** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
+**
+** In addition, as a special exception, Digia gives you certain additional
+** rights. These rights are described in the Digia Qt LGPL Exception
+** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
+**
+** GNU General Public License Usage
+** Alternatively, this file may be used under the terms of the GNU
+** General Public License version 3.0 as published by the Free Software
+** Foundation and appearing in the file LICENSE.GPL included in the
+** packaging of this file. Please review the following information to
+** ensure the GNU General Public License version 3.0 requirements will be
+** met: http://www.gnu.org/copyleft/gpl.html.
+**
+**
+** $QT_END_LICENSE$
+**
+****************************************************************************/
+
+#ifndef QFILEICONPROVIDER_P_H
+#define QFILEICONPROVIDER_P_H
+
+#include "qfileiconprovider.h"
+
+#include <QtCore/qstring.h>
+#include <QtGui/qicon.h>
+#include <QtWidgets/qstyle.h>
+
+QT_BEGIN_NAMESPACE
+
+class QFileInfo;
+
+class QFileIconProviderPrivate
+{
+ Q_DECLARE_PUBLIC(QFileIconProvider)
+
+public:
+ QFileIconProviderPrivate();
+ QIcon getIcon(QStyle::StandardPixmap name) const;
+ QIcon getIcon(const QFileInfo &fi) const;
+
+ QFileIconProvider *q_ptr;
+ const QString homePath;
+ QFileIconProvider::Options options;
+
+private:
+ mutable QIcon file;
+ mutable QIcon fileLink;
+ mutable QIcon directory;
+ mutable QIcon directoryLink;
+ mutable QIcon harddisk;
+ mutable QIcon floppy;
+ mutable QIcon cdrom;
+ mutable QIcon ram;
+ mutable QIcon network;
+ mutable QIcon computer;
+ mutable QIcon desktop;
+ mutable QIcon trashcan;
+ mutable QIcon generic;
+ mutable QIcon home;
+};
+
+QT_END_NAMESPACE
+
+#endif // QFILEICONPROVIDER_P_H
diff --git a/src/widgets/itemviews/qheaderview.cpp b/src/widgets/itemviews/qheaderview.cpp
index 864a55d2ea..75cd07bb80 100644
--- a/src/widgets/itemviews/qheaderview.cpp
+++ b/src/widgets/itemviews/qheaderview.cpp
@@ -80,6 +80,7 @@ QDataStream &operator>>(QDataStream &in, QHeaderViewPrivate::SectionItem &sectio
}
#endif // QT_NO_DATASTREAM
+static const int maxSizeSection = 1048575; // since section size is in a bitfield (uint 20). See qheaderview_p.h
/*!
\class QHeaderView
@@ -550,6 +551,22 @@ QSize QHeaderView::sizeHint() const
}
/*!
+ \reimp
+*/
+
+void QHeaderView::setVisible(bool v)
+{
+ bool actualChange = (v != isVisible());
+ QAbstractItemView::setVisible(v);
+ if (actualChange) {
+ QAbstractScrollArea *parent = qobject_cast<QAbstractScrollArea*>(parentWidget());
+ if (parent)
+ parent->updateGeometry();
+ }
+}
+
+
+/*!
Returns a suitable size hint for the section specified by \a logicalIndex.
\sa sizeHint(), defaultSectionSize(), minimumSectionSize(),
@@ -868,7 +885,7 @@ void QHeaderView::swapSections(int first, int second)
void QHeaderView::resizeSection(int logical, int size)
{
Q_D(QHeaderView);
- if (logical < 0 || logical >= count() || size < 0)
+ if (logical < 0 || logical >= count() || size < 0 || size > maxSizeSection)
return;
if (isSectionHidden(logical)) {
@@ -918,6 +935,18 @@ void QHeaderView::resizeSection(int logical, int size)
d->doDelayedResizeSections();
r = d->viewport->rect();
}
+
+ // If the parent is a QAbstractScrollArea with QAbstractScrollArea::AdjustToContents
+ // then we want to change the geometry on that widget. Not doing it at once can/will
+ // cause scrollbars flicker as they would be shown at first but then removed.
+ // In the same situation it will also allow shrinking the whole view when stretchLastSection is set
+ // (It is default on QTreeViews - and it wouldn't shrink since the last stretch was made before the
+ // viewport was resized)
+
+ QAbstractScrollArea *parent = qobject_cast<QAbstractScrollArea *>(parentWidget());
+ if (parent && parent->sizeAdjustPolicy() == QAbstractScrollArea::AdjustToContents)
+ parent->updateGeometry();
+
d->viewport->update(r.normalized());
emit sectionResized(logical, oldSize, size);
}
@@ -1225,7 +1254,7 @@ void QHeaderView::setSectionResizeMode(ResizeMode mode)
property is set to true. This is the default for the horizontal headers provided
by QTreeView.
- \sa setStretchLastSection()
+ \sa setStretchLastSection(), resizeContentsPrecision()
*/
void QHeaderView::setSectionResizeMode(int logicalIndex, ResizeMode mode)
@@ -1288,6 +1317,53 @@ QHeaderView::ResizeMode QHeaderView::sectionResizeMode(int logicalIndex) const
return d->headerSectionResizeMode(visual);
}
+/*!
+ \since 5.2
+ Sets how precise QHeaderView should calculate the size when ResizeToContents is used.
+ A low value will provide a less accurate but fast auto resize while a higher
+ value will provide a more accurate resize that however can be slow.
+
+ The number \a precision specifies how many sections that should be consider
+ when calculating the preferred size.
+
+ The default value is 1000 meaning that a horizontal column with auto-resize will look
+ at maximum 1000 rows on calculating when doing an auto resize.
+
+ Special value 0 means that it will look at only the visible area.
+ Special value -1 will imply looking at all elements.
+
+ This value is used in QTableView::sizeHintForColumn(), QTableView::sizeHintForRow()
+ and QTreeView::sizeHintForColumn(). Reimplementing these functions can make this
+ function not having an effect.
+
+ If \a resizeSectionsNow is set to true (default) it will do adjustment of sections by calling
+ resizeSections(). (regardless if the precision was changed).
+
+ \sa resizeContentsPrecision(), setSectionResizeMode(), resizeSections(), QTableView::sizeHintForColumn(), QTableView::sizeHintForRow(), QTreeView::sizeHintForColumn()
+*/
+
+void QHeaderView::setResizeContentsPrecision(int precision, bool resizeSectionsNow)
+{
+ Q_D(QHeaderView);
+ d->resizeContentsPrecision = precision;
+ if (resizeSectionsNow)
+ resizeSections();
+}
+
+/*!
+ \since 5.2
+ Returns how precise QHeaderView will calculate on ResizeToContents.
+
+ \sa setResizeContentsPrecision(), setSectionResizeMode()
+
+*/
+
+int QHeaderView::resizeContentsPrecision() const
+{
+ Q_D(const QHeaderView);
+ return d->resizeContentsPrecision;
+}
+
// ### Qt 6 - remove this obsolete function
/*!
\obsolete
@@ -1492,7 +1568,7 @@ int QHeaderView::defaultSectionSize() const
void QHeaderView::setDefaultSectionSize(int size)
{
Q_D(QHeaderView);
- if (size < 0)
+ if (size < 0 || size > maxSizeSection)
return;
d->setDefaultSectionSize(size);
}
@@ -1527,7 +1603,7 @@ int QHeaderView::minimumSectionSize() const
void QHeaderView::setMinimumSectionSize(int size)
{
Q_D(QHeaderView);
- if (size < 0)
+ if (size < 0 || size > maxSizeSection)
return;
d->minimumSectionSize = size;
}
@@ -3492,7 +3568,7 @@ QHeaderView::ResizeMode QHeaderViewPrivate::headerSectionResizeMode(int visual)
{
if (visual < 0 || visual >= sectionItems.count())
return globalResizeMode;
- return sectionItems.at(visual).resizeMode;
+ return static_cast<QHeaderView::ResizeMode>(sectionItems.at(visual).resizeMode);
}
void QHeaderViewPrivate::setGlobalHeaderResizeMode(QHeaderView::ResizeMode mode)
@@ -3530,6 +3606,19 @@ int QHeaderViewPrivate::adjustedVisualIndex(int visualIndex) const
return visualIndex;
}
+void QHeaderViewPrivate::setScrollOffset(const QScrollBar *scrollBar, QAbstractItemView::ScrollMode scrollMode)
+{
+ Q_Q(QHeaderView);
+ if (scrollMode == QAbstractItemView::ScrollPerItem) {
+ if (scrollBar->maximum() > 0 && scrollBar->value() == scrollBar->maximum())
+ q->setOffsetToLastSection();
+ else
+ q->setOffsetToSectionPosition(scrollBar->value());
+ } else {
+ q->setOffset(scrollBar->value());
+ }
+}
+
#ifndef QT_NO_DATASTREAM
void QHeaderViewPrivate::write(QDataStream &out) const
{
@@ -3560,6 +3649,8 @@ void QHeaderViewPrivate::write(QDataStream &out) const
out << int(globalResizeMode);
out << sectionItems;
+ if (out.version() >= QDataStream::Qt_5_2)
+ out << resizeContentsPrecision;
}
bool QHeaderViewPrivate::read(QDataStream &in)
@@ -3611,6 +3702,10 @@ bool QHeaderViewPrivate::read(QDataStream &in)
}
sectionItems = newSectionItems;
recalcSectionStartPos();
+
+ if (in.version() >= QDataStream::Qt_5_2)
+ in >> resizeContentsPrecision;
+
return true;
}
diff --git a/src/widgets/itemviews/qheaderview.h b/src/widgets/itemviews/qheaderview.h
index 8fcd8d7a36..3de3d320bf 100644
--- a/src/widgets/itemviews/qheaderview.h
+++ b/src/widgets/itemviews/qheaderview.h
@@ -84,6 +84,7 @@ public:
int offset() const;
int length() const;
QSize sizeHint() const;
+ void setVisible(bool v);
int sectionSizeHint(int logicalIndex) const;
int visualIndexAt(int position) const;
@@ -132,6 +133,10 @@ public:
ResizeMode sectionResizeMode(int logicalIndex) const;
void setSectionResizeMode(ResizeMode mode);
void setSectionResizeMode(int logicalIndex, ResizeMode mode);
+
+ void setResizeContentsPrecision(int precision, bool resizeNow = true);
+ int resizeContentsPrecision() const;
+
#if QT_DEPRECATED_SINCE(5, 0)
inline QT_DEPRECATED void setResizeMode(ResizeMode mode)
{ setSectionResizeMode(mode); }
diff --git a/src/widgets/itemviews/qheaderview_p.h b/src/widgets/itemviews/qheaderview_p.h
index f886430ba8..a8c620b9d2 100644
--- a/src/widgets/itemviews/qheaderview_p.h
+++ b/src/widgets/itemviews/qheaderview_p.h
@@ -99,7 +99,8 @@ public:
sectionIndicatorOffset(0),
sectionIndicator(0),
globalResizeMode(QHeaderView::Interactive),
- sectionStartposRecalc(true)
+ sectionStartposRecalc(true),
+ resizeContentsPrecision(1000)
{}
@@ -293,26 +294,31 @@ public:
QHeaderView::ResizeMode globalResizeMode;
QList<QPersistentModelIndex> persistentHiddenSections;
mutable bool sectionStartposRecalc;
+ int resizeContentsPrecision;
// header sections
struct SectionItem {
- int size;
+ uint size : 20;
+ uint reservedForIsHidden : 1;
+ uint resizeMode : 5; // (holding QHeaderView::ResizeMode)
+ uint currentlyUnusedPadding : 6;
+
union { // This union is made in order to save space and ensure good vector performance (on remove)
mutable int calculated_startpos; // <- this is the primary used member.
mutable int tmpLogIdx; // When one of these 'tmp'-members has been used we call
int tmpDataStreamSectionCount; // recalcSectionStartPos() or set sectionStartposRecalc to true
}; // to ensure that calculated_startpos will be calculated afterwards.
- QHeaderView::ResizeMode resizeMode;
+
inline SectionItem() : size(0), resizeMode(QHeaderView::Interactive) {}
inline SectionItem(int length, QHeaderView::ResizeMode mode)
- : size(length), calculated_startpos(-1), resizeMode(mode) {}
+ : size(length), resizeMode(mode), calculated_startpos(-1) {}
inline int sectionSize() const { return size; }
inline int calculatedEndPos() const { return calculated_startpos + size; }
#ifndef QT_NO_DATASTREAM
inline void write(QDataStream &out) const
- { out << size; out << 1; out << (int)resizeMode; }
+ { out << static_cast<int>(size); out << 1; out << (int)resizeMode; }
inline void read(QDataStream &in)
- { in >> size; in >> tmpDataStreamSectionCount; int m; in >> m; resizeMode = (QHeaderView::ResizeMode)m; }
+ { int m; in >> m; size = m; in >> tmpDataStreamSectionCount; in >> m; resizeMode = m; }
#endif
};
@@ -343,6 +349,7 @@ public:
// other
int viewSectionSizeHint(int logical) const;
int adjustedVisualIndex(int visualIndex) const;
+ void setScrollOffset(const QScrollBar *scrollBar, QAbstractItemView::ScrollMode scrollMode);
#ifndef QT_NO_DATASTREAM
void write(QDataStream &out) const;
diff --git a/src/widgets/itemviews/qlistview.cpp b/src/widgets/itemviews/qlistview.cpp
index 8ccb0557cb..32c63b9f93 100644
--- a/src/widgets/itemviews/qlistview.cpp
+++ b/src/widgets/itemviews/qlistview.cpp
@@ -1835,16 +1835,16 @@ void QCommonListViewBase::removeHiddenRow(int row)
void QCommonListViewBase::updateHorizontalScrollBar(const QSize &step)
{
- horizontalScrollBar()->setSingleStep(step.width() + spacing());
horizontalScrollBar()->setPageStep(viewport()->width());
horizontalScrollBar()->setRange(0, contentsSize.width() - viewport()->width());
+ // we do not want to overwrite (a possible user set) single step
}
-void QCommonListViewBase::updateVerticalScrollBar(const QSize &step)
+void QCommonListViewBase::updateVerticalScrollBar(const QSize & /*step*/)
{
- verticalScrollBar()->setSingleStep(step.height() + spacing());
verticalScrollBar()->setPageStep(viewport()->height());
verticalScrollBar()->setRange(0, contentsSize.height() - viewport()->height());
+ // we do not want to overwrite (a possible user set) single step
}
void QCommonListViewBase::scrollContentsBy(int dx, int dy, bool /*scrollElasticBand*/)
diff --git a/src/widgets/itemviews/qlistwidget.cpp b/src/widgets/itemviews/qlistwidget.cpp
index 39d03124ce..1573e97981 100644
--- a/src/widgets/itemviews/qlistwidget.cpp
+++ b/src/widgets/itemviews/qlistwidget.cpp
@@ -347,7 +347,11 @@ void QListModel::ensureSorted(int column, Qt::SortOrder order, int start, int en
bool changed = false;
for (int i = 0; i < count; ++i) {
int oldRow = sorting.at(i).second;
+ int tmpitepos = lit - tmp.begin();
QListWidgetItem *item = tmp.takeAt(oldRow);
+ if (tmpitepos > tmp.size())
+ --tmpitepos;
+ lit = tmp.begin() + tmpitepos;
lit = sortedInsertionIterator(lit, tmp.end(), order, item);
int newRow = qMax(lit - tmp.begin(), 0);
lit = tmp.insert(lit, item);
diff --git a/src/widgets/itemviews/qtableview.cpp b/src/widgets/itemviews/qtableview.cpp
index a6623b9462..871ad656ea 100644
--- a/src/widgets/itemviews/qtableview.cpp
+++ b/src/widgets/itemviews/qtableview.cpp
@@ -931,6 +931,59 @@ void QTableViewPrivate::drawCell(QPainter *painter, const QStyleOptionViewItem &
}
/*!
+ \internal
+ Get sizeHint width for single Index (providing existing hint and style option)
+*/
+int QTableViewPrivate::widthHintForIndex(const QModelIndex &index, int hint, const QStyleOptionViewItem &option) const
+{
+ Q_Q(const QTableView);
+ QWidget *editor = editorForIndex(index).widget.data();
+ if (editor && persistent.contains(editor)) {
+ hint = qMax(hint, editor->sizeHint().width());
+ int min = editor->minimumSize().width();
+ int max = editor->maximumSize().width();
+ hint = qBound(min, hint, max);
+ }
+ hint = qMax(hint, q->itemDelegate(index)->sizeHint(option, index).width());
+ return hint;
+}
+
+/*!
+ \internal
+ Get sizeHint height for single Index (providing existing hint and style option)
+*/
+int QTableViewPrivate::heightHintForIndex(const QModelIndex &index, int hint, QStyleOptionViewItem &option) const
+{
+ Q_Q(const QTableView);
+ QWidget *editor = editorForIndex(index).widget.data();
+ if (editor && persistent.contains(editor)) {
+ hint = qMax(hint, editor->sizeHint().height());
+ int min = editor->minimumSize().height();
+ int max = editor->maximumSize().height();
+ hint = qBound(min, hint, max);
+ }
+
+ if (wrapItemText) {// for wrapping boundaries
+ option.rect.setY(q->rowViewportPosition(index.row()));
+ int height = q->rowHeight(index.row());
+ // if the option.height == 0 then q->itemDelegate(index)->sizeHint(option, index) will be wrong.
+ // The option.height == 0 is used to conclude that the text is not wrapped, and hence it will
+ // (exactly like widthHintForIndex) return a QSize with a long width (that we don't use) -
+ // and the height of the text if it was/is on one line.
+ // What we want is a height hint for the current width (and we know that this section is not hidden)
+ // Therefore we catch this special situation with:
+ if (height == 0)
+ height = 1;
+ option.rect.setHeight(height);
+ option.rect.setX(q->columnViewportPosition(index.column()));
+ option.rect.setWidth(q->columnWidth(index.column()));
+ }
+ hint = qMax(hint, q->itemDelegate(index)->sizeHint(option, index).height());
+ return hint;
+}
+
+
+/*!
\class QTableView
\brief The QTableView class provides a default model/view
@@ -1056,6 +1109,19 @@ QTableView::~QTableView()
/*!
\reimp
*/
+QSize QTableView::viewportSizeHint() const
+{
+ Q_D(const QTableView);
+ QSize result( (d->verticalHeader->isHidden() ? 0 : d->verticalHeader->width()) + d->horizontalHeader->length(),
+ (d->horizontalHeader->isHidden() ? 0 : d->horizontalHeader->height()) + d->verticalHeader->length());
+ result += QSize(verticalScrollBar()->isVisible() ? verticalScrollBar()->width() : 0,
+ horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0);
+ return result;
+}
+
+/*!
+ \reimp
+*/
void QTableView::setModel(QAbstractItemModel *model)
{
Q_D(QTableView);
@@ -1113,15 +1179,7 @@ void QTableView::doItemsLayout()
{
Q_D(QTableView);
QAbstractItemView::doItemsLayout();
- if (verticalScrollMode() == QAbstractItemView::ScrollPerItem) {
- const int max = verticalScrollBar()->maximum();
- if (max > 0 && verticalScrollBar()->value() == max)
- d->verticalHeader->setOffsetToLastSection();
- else
- d->verticalHeader->setOffsetToSectionPosition(verticalScrollBar()->value());
- } else {
- d->verticalHeader->setOffset(verticalScrollBar()->value());
- }
+ d->verticalHeader->d_func()->setScrollOffset(verticalScrollBar(), verticalScrollMode());
if (!d->verticalHeader->updatesEnabled())
d->verticalHeader->setUpdatesEnabled(true);
}
@@ -1258,29 +1316,19 @@ void QTableView::scrollContentsBy(int dx, int dy)
dx = isRightToLeft() ? -dx : dx;
if (dx) {
+ int oldOffset = d->horizontalHeader->offset();
+ d->horizontalHeader->d_func()->setScrollOffset(horizontalScrollBar(), horizontalScrollMode());
if (horizontalScrollMode() == QAbstractItemView::ScrollPerItem) {
- int oldOffset = d->horizontalHeader->offset();
- if (horizontalScrollBar()->value() == horizontalScrollBar()->maximum())
- d->horizontalHeader->setOffsetToLastSection();
- else
- d->horizontalHeader->setOffsetToSectionPosition(horizontalScrollBar()->value());
int newOffset = d->horizontalHeader->offset();
dx = isRightToLeft() ? newOffset - oldOffset : oldOffset - newOffset;
- } else {
- d->horizontalHeader->setOffset(horizontalScrollBar()->value());
}
}
if (dy) {
+ int oldOffset = d->verticalHeader->offset();
+ d->verticalHeader->d_func()->setScrollOffset(verticalScrollBar(), verticalScrollMode());
if (verticalScrollMode() == QAbstractItemView::ScrollPerItem) {
- int oldOffset = d->verticalHeader->offset();
- if (verticalScrollBar()->value() == verticalScrollBar()->maximum())
- d->verticalHeader->setOffsetToLastSection();
- else
- d->verticalHeader->setOffsetToSectionPosition(verticalScrollBar()->value());
int newOffset = d->verticalHeader->offset();
dy = oldOffset - newOffset;
- } else {
- d->verticalHeader->setOffset(verticalScrollBar()->value());
}
}
d->scrollContentsBy(dx, dy);
@@ -1760,13 +1808,13 @@ QModelIndex QTableView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifi
visualRow = bottom;
break;
case MovePageUp: {
- int newRow = rowAt(visualRect(current).top() - d->viewport->height());
+ int newRow = rowAt(visualRect(current).bottom() - d->viewport->height());
if (newRow == -1)
newRow = d->logicalRow(0);
return d->model->index(newRow, current.column(), d->root);
}
case MovePageDown: {
- int newRow = rowAt(visualRect(current).bottom() + d->viewport->height());
+ int newRow = rowAt(visualRect(current).top() + d->viewport->height());
if (newRow == -1)
newRow = d->logicalRow(bottom);
return d->model->index(newRow, current.column(), d->root);
@@ -2128,7 +2176,7 @@ void QTableView::updateGeometries()
} else { // ScrollPerPixel
horizontalScrollBar()->setPageStep(vsize.width());
horizontalScrollBar()->setRange(0, horizontalLength - vsize.width());
- horizontalScrollBar()->setSingleStep(qMax(vsize.width() / (columnsInViewport + 1), 2));
+ // here we do not want to overwrite (a possible user set) single step
}
// vertical scroll bar
@@ -2156,7 +2204,7 @@ void QTableView::updateGeometries()
} else { // ScrollPerPixel
verticalScrollBar()->setPageStep(vsize.height());
verticalScrollBar()->setRange(0, verticalLength - vsize.height());
- verticalScrollBar()->setSingleStep(qMax(vsize.height() / (rowsInViewport + 1), 2));
+ // here we do not want to overwrite (a possible user set) single step
}
d->geometryRecursionBlock = false;
@@ -2175,7 +2223,7 @@ void QTableView::updateGeometries()
if a larger row height is required by either the vertical header or
the item delegate, that width will be used instead.
- \sa QWidget::sizeHint, verticalHeader()
+ \sa QWidget::sizeHint, verticalHeader(), QHeaderView::resizeContentsPrecision()
*/
int QTableView::sizeHintForRow(int row) const
{
@@ -2185,6 +2233,8 @@ int QTableView::sizeHintForRow(int row) const
return -1;
ensurePolished();
+ const int maximumProcessCols = d->verticalHeader->resizeContentsPrecision();
+
int left = qMax(0, d->horizontalHeader->visualIndexAt(0));
int right = d->horizontalHeader->visualIndexAt(d->viewport->width());
@@ -2195,27 +2245,55 @@ int QTableView::sizeHintForRow(int row) const
int hint = 0;
QModelIndex index;
- for (int column = left; column <= right; ++column) {
+ int columnsProcessed = 0;
+ int column = left;
+ for (; column <= right; ++column) {
int logicalColumn = d->horizontalHeader->logicalIndex(column);
if (d->horizontalHeader->isSectionHidden(logicalColumn))
continue;
index = d->model->index(row, logicalColumn, d->root);
- if (d->wrapItemText) {// for wrapping boundaries
- option.rect.setY(rowViewportPosition(index.row()));
- option.rect.setHeight(rowHeight(index.row()));
- option.rect.setX(columnViewportPosition(index.column()));
- option.rect.setWidth(columnWidth(index.column()));
- }
+ hint = d->heightHintForIndex(index, hint, option);
+
+ ++columnsProcessed;
+ if (columnsProcessed == maximumProcessCols)
+ break;
+ }
- QWidget *editor = d->editorForIndex(index).widget.data();
- if (editor && d->persistent.contains(editor)) {
- hint = qMax(hint, editor->sizeHint().height());
- int min = editor->minimumSize().height();
- int max = editor->maximumSize().height();
- hint = qBound(min, hint, max);
+ int actualRight = d->model->columnCount(d->root) - 1;
+ int idxLeft = left;
+ int idxRight = column - 1;
+
+ if (maximumProcessCols == 0)
+ columnsProcessed = 0; // skip the while loop
+
+ while (columnsProcessed != maximumProcessCols && (idxLeft > 0 || idxRight < actualRight)) {
+ int logicalIdx = -1;
+
+ if ((columnsProcessed % 2 && idxLeft > 0) || idxRight == actualRight) {
+ while (idxLeft > 0) {
+ --idxLeft;
+ int logcol = d->horizontalHeader->logicalIndex(idxLeft);
+ if (d->horizontalHeader->isSectionHidden(logcol))
+ continue;
+ logicalIdx = logcol;
+ break;
+ }
+ } else {
+ while (idxRight < actualRight) {
+ ++idxRight;
+ int logcol = d->horizontalHeader->logicalIndex(idxRight);
+ if (d->horizontalHeader->isSectionHidden(logcol))
+ continue;
+ logicalIdx = logcol;
+ break;
+ }
}
+ if (logicalIdx < 0)
+ continue;
- hint = qMax(hint, itemDelegate(index)->sizeHint(option, index).height());
+ index = d->model->index(row, logicalIdx, d->root);
+ hint = d->heightHintForIndex(index, hint, option);
+ ++columnsProcessed;
}
return d->showGrid ? hint + 1 : hint;
@@ -2234,7 +2312,7 @@ int QTableView::sizeHintForRow(int row) const
required by either the horizontal header or the item delegate, the larger
width will be used instead.
- \sa QWidget::sizeHint, horizontalHeader()
+ \sa QWidget::sizeHint, horizontalHeader(), QHeaderView::resizeContentsPrecision()
*/
int QTableView::sizeHintForColumn(int column) const
{
@@ -2244,6 +2322,7 @@ int QTableView::sizeHintForColumn(int column) const
return -1;
ensurePolished();
+ const int maximumProcessRows = d->horizontalHeader->resizeContentsPrecision();
int top = qMax(0, d->verticalHeader->visualIndexAt(0));
int bottom = d->verticalHeader->visualIndexAt(d->viewport->height());
@@ -2253,22 +2332,56 @@ int QTableView::sizeHintForColumn(int column) const
QStyleOptionViewItem option = d->viewOptions();
int hint = 0;
+ int rowsProcessed = 0;
QModelIndex index;
- for (int row = top; row <= bottom; ++row) {
+ int row = top;
+ for (; row <= bottom; ++row) {
int logicalRow = d->verticalHeader->logicalIndex(row);
if (d->verticalHeader->isSectionHidden(logicalRow))
continue;
index = d->model->index(logicalRow, column, d->root);
- QWidget *editor = d->editorForIndex(index).widget.data();
- if (editor && d->persistent.contains(editor)) {
- hint = qMax(hint, editor->sizeHint().width());
- int min = editor->minimumSize().width();
- int max = editor->maximumSize().width();
- hint = qBound(min, hint, max);
+ hint = d->widthHintForIndex(index, hint, option);
+ ++rowsProcessed;
+ if (rowsProcessed == maximumProcessRows)
+ break;
+ }
+
+ int actualBottom = d->model->rowCount(d->root) - 1;
+ int idxTop = top;
+ int idxBottom = row - 1;
+
+ if (maximumProcessRows == 0)
+ rowsProcessed = 0; // skip the while loop
+
+ while (rowsProcessed != maximumProcessRows && (idxTop > 0 || idxBottom < actualBottom)) {
+ int logicalIdx = -1;
+
+ if ((rowsProcessed % 2 && idxTop > 0) || idxBottom == actualBottom) {
+ while (idxTop > 0) {
+ --idxTop;
+ int logrow = d->verticalHeader->logicalIndex(idxTop);
+ if (d->verticalHeader->isSectionHidden(logrow))
+ continue;
+ logicalIdx = logrow;
+ break;
+ }
+ } else {
+ while (idxBottom < actualBottom) {
+ ++idxBottom;
+ int logrow = d->verticalHeader->logicalIndex(idxBottom);
+ if (d->verticalHeader->isSectionHidden(logrow))
+ continue;
+ logicalIdx = logrow;
+ break;
+ }
}
+ if (logicalIdx < 0)
+ continue;
- hint = qMax(hint, itemDelegate(index)->sizeHint(option, index).width());
+ index = d->model->index(logicalIdx, column, d->root);
+ hint = d->widthHintForIndex(index, hint, option);
+ ++rowsProcessed;
}
return d->showGrid ? hint + 1 : hint;
@@ -2934,6 +3047,8 @@ void QTableView::showColumn(int column)
/*!
Resizes the given \a row based on the size hints of the delegate
used to render each item in the row.
+
+ \sa resizeRowsToContents(), sizeHintForRow(), QHeaderView::resizeContentsPrecision()
*/
void QTableView::resizeRowToContents(int row)
{
@@ -2946,6 +3061,8 @@ void QTableView::resizeRowToContents(int row)
/*!
Resizes all rows based on the size hints of the delegate
used to render each item in the rows.
+
+ \sa resizeRowToContents(), sizeHintForRow(), QHeaderView::resizeContentsPrecision()
*/
void QTableView::resizeRowsToContents()
{
@@ -2959,6 +3076,8 @@ void QTableView::resizeRowsToContents()
\note Only visible columns will be resized. Reimplement sizeHintForColumn()
to resize hidden columns as well.
+
+ \sa resizeColumnsToContents(), sizeHintForColumn(), QHeaderView::resizeContentsPrecision()
*/
void QTableView::resizeColumnToContents(int column)
{
@@ -2971,6 +3090,8 @@ void QTableView::resizeColumnToContents(int column)
/*!
Resizes all columns based on the size hints of the delegate
used to render each item in the columns.
+
+ \sa resizeColumnToContents(), sizeHintForColumn(), QHeaderView::resizeContentsPrecision()
*/
void QTableView::resizeColumnsToContents()
{
diff --git a/src/widgets/itemviews/qtableview.h b/src/widgets/itemviews/qtableview.h
index 824348dbe8..db956480d6 100644
--- a/src/widgets/itemviews/qtableview.h
+++ b/src/widgets/itemviews/qtableview.h
@@ -118,6 +118,8 @@ public:
void sortByColumn(int column, Qt::SortOrder order);
+ QSize viewportSizeHint() const;
+
public Q_SLOTS:
void selectRow(int row);
void selectColumn(int column);
diff --git a/src/widgets/itemviews/qtableview_p.h b/src/widgets/itemviews/qtableview_p.h
index 923beec253..d36dcd2c3a 100644
--- a/src/widgets/itemviews/qtableview_p.h
+++ b/src/widgets/itemviews/qtableview_p.h
@@ -181,6 +181,8 @@ public:
const QStyleOptionViewItem &option, QBitArray *drawn,
int firstVisualRow, int lastVisualRow, int firstVisualColumn, int lastVisualColumn);
void drawCell(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index);
+ int widthHintForIndex(const QModelIndex &index, int hint, const QStyleOptionViewItem &option) const;
+ int heightHintForIndex(const QModelIndex &index, int hint, QStyleOptionViewItem &option) const;
bool showGrid;
Qt::PenStyle gridStyle;
diff --git a/src/widgets/itemviews/qtreeview.cpp b/src/widgets/itemviews/qtreeview.cpp
index 6aefbb5367..54b663274d 100644
--- a/src/widgets/itemviews/qtreeview.cpp
+++ b/src/widgets/itemviews/qtreeview.cpp
@@ -335,6 +335,7 @@ void QTreeView::setHeader(QHeaderView *header)
this, SLOT(updateGeometries()));
setSortingEnabled(d->sortingEnabled);
+ d->updateGeometry();
}
/*!
@@ -952,6 +953,36 @@ bool QTreeView::wordWrap() const
return d->wrapItemText;
}
+/*!
+ \since 5.2
+
+ This specifies that the tree structure should be placed at logical index \a index.
+ If \index is set to -1 then the tree will always follow visual index 0.
+
+ \sa treePosition(), QHeaderView::swapSections(), QHeaderView::moveSection()
+*/
+
+void QTreeView::setTreePosition(int index)
+{
+ Q_D(QTreeView);
+ d->treePosition = index;
+ update();
+}
+
+/*!
+ \since 5.2
+
+ Return the logical index the tree is set on. If the return value is -1 then the
+ tree is placed on the visual index 0.
+
+ \sa setTreePosition()
+*/
+
+int QTreeView::treePosition() const
+{
+ Q_D(const QTreeView);
+ return d->treePosition;
+}
/*!
\reimp
@@ -1067,7 +1098,7 @@ QRect QTreeView::visualRect(const QModelIndex &index) const
int x = (spanning ? 0 : columnViewportPosition(index.column()));
int w = (spanning ? d->header->length() : columnWidth(index.column()));
// handle indentation
- if (index.column() == 0) {
+ if (d->isTreePosition(index.column())) {
int i = d->indentationForItem(vi);
w -= i;
if (!isRightToLeft())
@@ -1284,6 +1315,14 @@ void QTreeView::paintEvent(QPaintEvent *event)
}
}
+int QTreeViewPrivate::logicalIndexForTree() const
+{
+ int index = treePosition;
+ if (index < 0)
+ index = header->logicalIndex(0);
+ return index;
+}
+
void QTreeViewPrivate::paintAlternatingRowColors(QPainter *painter, QStyleOptionViewItem *option, int y, int bottom) const
{
Q_Q(const QTreeView);
@@ -1516,7 +1555,7 @@ void QTreeViewPrivate::calcLogicalIndices(QVector<int> *logicalIndices, QVector<
if (columnCount == 1 || (nextLogicalSection == 0 && prevLogicalSection == -1)
|| (headerSection == 0 && nextLogicalSection == -1) || spanning)
pos = QStyleOptionViewItem::OnlyOne;
- else if (headerSection == 0 || (nextLogicalSection != 0 && prevLogicalSection == -1))
+ else if (isTreePosition(headerSection) || (nextLogicalSection != 0 && prevLogicalSection == -1))
pos = QStyleOptionViewItem::Beginning;
else if (nextLogicalSection == 0 || nextLogicalSection == -1)
pos = QStyleOptionViewItem::End;
@@ -1526,6 +1565,23 @@ void QTreeViewPrivate::calcLogicalIndices(QVector<int> *logicalIndices, QVector<
}
}
+/*!
+ \internal
+ Get sizeHint width for single index (providing existing hint and style option) and index in viewIndex i.
+*/
+int QTreeViewPrivate::widthHintForIndex(const QModelIndex &index, int hint, const QStyleOptionViewItem &option, int i) const
+{
+ QWidget *editor = editorForIndex(index).widget.data();
+ if (editor && persistent.contains(editor)) {
+ hint = qMax(hint, editor->sizeHint().width());
+ int min = editor->minimumSize().width();
+ int max = editor->maximumSize().width();
+ hint = qBound(min, hint, max);
+ }
+ int xhint = delegateForIndex(index)->sizeHint(option, index).width();
+ hint = qMax(hint, xhint + (isTreePosition(index.column()) ? indentationForItem(i) : 0));
+ return hint;
+}
/*!
Draws the row in the tree view that contains the model item \a index,
@@ -1668,7 +1724,7 @@ void QTreeView::drawRow(QPainter *painter, const QStyleOptionViewItem &option,
alternate row color was provided by the view. For backward compatibility,
this is now delegated to the style using PE_PanelViewItemRow which
does the appropriate fill */
- if (headerSection == 0) {
+ if (d->isTreePosition(headerSection)) {
const int i = d->indentationForItem(d->current);
QRect branches(reverse ? position + width - i : position, y, i, height);
const bool setClipRect = branches.width() > width;
@@ -2400,16 +2456,11 @@ void QTreeView::scrollContentsBy(int dx, int dy)
dx = isRightToLeft() ? -dx : dx;
if (dx) {
+ int oldOffset = d->header->offset();
+ d->header->d_func()->setScrollOffset(horizontalScrollBar(), horizontalScrollMode());
if (horizontalScrollMode() == QAbstractItemView::ScrollPerItem) {
- int oldOffset = d->header->offset();
- if (horizontalScrollBar()->value() == horizontalScrollBar()->maximum())
- d->header->setOffsetToLastSection();
- else
- d->header->setOffsetToSectionPosition(horizontalScrollBar()->value());
int newOffset = d->header->offset();
dx = isRightToLeft() ? newOffset - oldOffset : oldOffset - newOffset;
- } else {
- d->header->setOffset(horizontalScrollBar()->value());
}
}
@@ -2552,7 +2603,7 @@ void QTreeView::columnCountChanged(int oldCount, int newCount)
/*!
Resizes the \a column given to the size of its contents.
- \sa columnWidth(), setColumnWidth()
+ \sa columnWidth(), setColumnWidth(), sizeHintForColumn(), QHeaderView::resizeContentsPrecision()
*/
void QTreeView::resizeColumnToContents(int column)
{
@@ -2619,6 +2670,35 @@ void QTreeView::selectAll()
}
/*!
+ \reimp
+*/
+QSize QTreeView::viewportSizeHint() const
+{
+ Q_D(const QTreeView);
+ d->executePostedLayout(); // Make sure that viewItems are up to date.
+
+ if (d->viewItems.size() == 0)
+ return QAbstractItemView::viewportSizeHint();
+
+ // Get rect for last item
+ const QRect deepestRect = visualRect(d->viewItems.last().index);
+
+ if (!deepestRect.isValid())
+ return QAbstractItemView::viewportSizeHint();
+
+ QSize result = QSize(d->header->length(), deepestRect.bottom() + 1);
+
+ // add size for header
+ result += QSize(0, d->header->isVisible() ? d->header->height() : 0);
+
+ // add size for scrollbars
+ result += QSize(verticalScrollBar()->isVisible() ? verticalScrollBar()->width() : 0,
+ horizontalScrollBar()->isVisible() ? horizontalScrollBar()->height() : 0);
+
+ return result;
+}
+
+/*!
\since 4.2
Expands all expandable items.
@@ -2740,7 +2820,6 @@ void QTreeView::updateGeometries()
QRect vg = d->viewport->geometry();
QRect geometryRect(vg.left(), vg.top() - hint.height(), vg.width(), hint.height());
d->header->setGeometry(geometryRect);
- //d->header->setOffset(horizontalScrollBar()->value()); // ### bug ???
QMetaObject::invokeMethod(d->header, "updateGeometries");
d->updateScrollBars();
d->geometryRecursionBlock = false;
@@ -2760,7 +2839,7 @@ void QTreeView::updateGeometries()
if a larger column width is required by either the view's header or
the item delegate, that width will be used instead.
- \sa QWidget::sizeHint, header()
+ \sa QWidget::sizeHint, header(), QHeaderView::resizeContentsPrecision()
*/
int QTreeView::sizeHintForColumn(int column) const
{
@@ -2773,28 +2852,58 @@ int QTreeView::sizeHintForColumn(int column) const
QStyleOptionViewItem option = d->viewOptions();
const QVector<QTreeViewItem> viewItems = d->viewItems;
- int start = 0;
- int end = viewItems.count();
- if(end > 1000) { //if we have too many item this function would be too slow.
- //we get a good approximation by only iterate over 1000 items.
- start = qMax(0, d->firstVisibleItem() - 100);
- end = qMin(end, start + 900);
- }
+ const int maximumProcessRows = d->header->resizeContentsPrecision(); // To avoid this to take forever.
+
+ int offset = 0;
+ int start = d->firstVisibleItem(&offset);
+ int end = d->lastVisibleItem(start, offset);
- for (int i = start; i < end; ++i) {
+ int rowsProcessed = 0;
+
+ for (int i = start; i <= end; ++i) {
if (viewItems.at(i).spanning)
continue; // we have no good size hint
QModelIndex index = viewItems.at(i).index;
index = index.sibling(index.row(), column);
- QWidget *editor = d->editorForIndex(index).widget.data();
- if (editor && d->persistent.contains(editor)) {
- w = qMax(w, editor->sizeHint().width());
- int min = editor->minimumSize().width();
- int max = editor->maximumSize().width();
- w = qBound(min, w, max);
+ w = d->widthHintForIndex(index, w, option, i);
+ ++rowsProcessed;
+ if (rowsProcessed == maximumProcessRows)
+ break;
+ }
+
+ --end;
+ int actualBottom = viewItems.size() - 1;
+
+ if (maximumProcessRows == 0)
+ rowsProcessed = 0; // skip the while loop
+
+ while (rowsProcessed != maximumProcessRows && (start > 0 || end < actualBottom)) {
+ int idx = -1;
+
+ if ((rowsProcessed % 2 && start > 0) || end == actualBottom) {
+ while (start > 0) {
+ --start;
+ if (viewItems.at(start).spanning)
+ continue;
+ idx = start;
+ break;
+ }
+ } else {
+ while (end < actualBottom) {
+ ++end;
+ if (viewItems.at(end).spanning)
+ continue;
+ idx = end;
+ break;
+ }
}
- int hint = d->delegateForIndex(index)->sizeHint(option, index).width();
- w = qMax(w, hint + (column == 0 ? d->indentationForItem(i) : 0));
+ if (idx < 0)
+ continue;
+
+ QModelIndex index = viewItems.at(idx).index;
+ index = index.sibling(index.row(), column);
+ w = d->widthHintForIndex(index, w, option, idx);
+ ++rowsProcessed;
}
return w;
}
@@ -2915,6 +3024,7 @@ void QTreeViewPrivate::initialize()
header->setDefaultAlignment(Qt::AlignLeft|Qt::AlignVCenter);
q->setHeader(header);
#ifndef QT_NO_ANIMATION
+ animationsEnabled = q->style()->styleHint(QStyle::SH_Widget_Animate, 0, q);
QObject::connect(&animatedOperation, SIGNAL(finished()), q, SLOT(_q_endAnimatedOperation()));
#endif //QT_NO_ANIMATION
}
@@ -3314,7 +3424,7 @@ int QTreeViewPrivate::coordinateForItem(int item) const
if (verticalScrollMode == QAbstractItemView::ScrollPerPixel) {
if (uniformRowHeights)
return (item * defaultItemHeight) - vbar->value();
- // ### optimize (spans or caching)
+ // ### optimize (maybe do like QHeaderView by letting items have startposition)
int y = 0;
for (int i = 0; i < viewItems.count(); ++i) {
if (i == item)
@@ -3481,7 +3591,7 @@ int QTreeViewPrivate::firstVisibleItem(int *offset) const
*offset = -(value % defaultItemHeight);
return value / defaultItemHeight;
}
- int y = 0; // ### optimize (use spans ?)
+ int y = 0; // ### (maybe do like QHeaderView by letting items have startposition)
for (int i = 0; i < viewItems.count(); ++i) {
y += itemHeight(i); // the height value is cached
if (y > value) {
@@ -3493,6 +3603,21 @@ int QTreeViewPrivate::firstVisibleItem(int *offset) const
return -1;
}
+int QTreeViewPrivate::lastVisibleItem(int firstVisual, int offset) const
+{
+ if (firstVisual < 0 || offset < 0)
+ firstVisual = firstVisibleItem(&offset);
+ int y = - offset;
+ int value = viewport->height();
+
+ for (int i = firstVisual; i < viewItems.count(); ++i) {
+ y += itemHeight(i); // the height value is cached
+ if (y > value)
+ return i;
+ }
+ return viewItems.size() - 1;
+}
+
int QTreeViewPrivate::columnAt(int x) const
{
return header->logicalIndexAt(x);
@@ -3535,13 +3660,13 @@ void QTreeViewPrivate::updateScrollBars()
int contentsHeight = 0;
if (uniformRowHeights) {
contentsHeight = defaultItemHeight * viewItems.count();
- } else { // ### optimize (spans or caching)
+ } else { // ### (maybe do like QHeaderView by letting items have startposition)
for (int i = 0; i < viewItems.count(); ++i)
contentsHeight += itemHeight(i);
}
vbar->setRange(0, contentsHeight - viewportSize.height());
vbar->setPageStep(viewportSize.height());
- vbar->setSingleStep(qMax(viewportSize.height() / (itemsInViewport + 1), 2));
+ // here we do not want to overwrite (a possible user set) single step
}
const int columnCount = header->count();
@@ -3567,7 +3692,7 @@ void QTreeViewPrivate::updateScrollBars()
viewportSize = maxSize;
hbar->setPageStep(viewportSize.width());
hbar->setRange(0, qMax(horizontalLength - viewportSize.width(), 0));
- hbar->setSingleStep(qMax(viewportSize.width() / (columnsInViewport + 1), 2));
+ // here we do not want to overwrite (a possible user set) single step
}
}
@@ -3576,7 +3701,7 @@ int QTreeViewPrivate::itemDecorationAt(const QPoint &pos) const
executePostedLayout();
int x = pos.x();
int column = header->logicalIndexAt(x);
- if (column != 0)
+ if (!isTreePosition(column))
return -1; // no logical index at x
int viewItemIndex = itemAtCoordinate(pos.y());
@@ -3598,8 +3723,8 @@ QRect QTreeViewPrivate::itemDecorationRect(const QModelIndex &index) const
return QRect();
int itemIndentation = indentationForItem(viewItemIndex);
- int position = header->sectionViewportPosition(0);
- int size = header->sectionSize(0);
+ int position = header->sectionViewportPosition(logicalIndexForTree());
+ int size = header->sectionSize(logicalIndexForTree());
QRect rect;
if (q->isRightToLeft())
diff --git a/src/widgets/itemviews/qtreeview.h b/src/widgets/itemviews/qtreeview.h
index 73f11f1a48..d9c6cd9269 100644
--- a/src/widgets/itemviews/qtreeview.h
+++ b/src/widgets/itemviews/qtreeview.h
@@ -128,6 +128,9 @@ public:
void setWordWrap(bool on);
bool wordWrap() const;
+ void setTreePosition(int logicalIndex);
+ int treePosition() const;
+
void keyboardSearch(const QString &search);
QRect visualRect(const QModelIndex &index) const;
@@ -144,6 +147,8 @@ public:
void dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QVector<int> &roles = QVector<int>());
void selectAll();
+ QSize viewportSizeHint() const;
+
Q_SIGNALS:
void expanded(const QModelIndex &index);
void collapsed(const QModelIndex &index);
diff --git a/src/widgets/itemviews/qtreeview_p.h b/src/widgets/itemviews/qtreeview_p.h
index 90e83cb58c..89de435606 100644
--- a/src/widgets/itemviews/qtreeview_p.h
+++ b/src/widgets/itemviews/qtreeview_p.h
@@ -91,10 +91,16 @@ public:
expandsOnDoubleClick(true),
allColumnsShowFocus(false), current(0), spanning(false),
animationsEnabled(false), columnResizeTimerID(0),
- autoExpandDelay(-1), hoverBranch(-1), geometryRecursionBlock(false), hasRemovedItems(false) {}
+ autoExpandDelay(-1), hoverBranch(-1), geometryRecursionBlock(false), hasRemovedItems(false),
+ treePosition(0) {}
~QTreeViewPrivate() {}
void initialize();
+ int logicalIndexForTree() const;
+ inline bool isTreePosition(int logicalIndex) const
+ {
+ return logicalIndex == logicalIndexForTree();
+ }
QItemViewPaintPairs draggablePaintPairs(const QModelIndexList &indexes, QRect *r) const;
void adjustViewOptionsForIndex(QStyleOptionViewItem *option, const QModelIndex &current) const;
@@ -148,6 +154,7 @@ public:
#endif
int firstVisibleItem(int *offset = 0) const;
+ int lastVisibleItem(int firstVisual = -1, int offset = -1) const;
int columnAt(int x) const;
bool hasVisibleChildren( const QModelIndex& parent) const;
@@ -171,7 +178,7 @@ public:
// logicalIndices: vector of currently visibly logical indices
// itemPositions: vector of view item positions (beginning/middle/end/onlyone)
void calcLogicalIndices(QVector<int> *logicalIndices, QVector<QStyleOptionViewItem::ViewItemPosition> *itemPositions, int left, int right) const;
-
+ int widthHintForIndex(const QModelIndex &index, int hint, const QStyleOptionViewItem &option, int i) const;
QHeaderView *header;
int indent;
@@ -251,6 +258,9 @@ public:
// If we should clean the set
bool hasRemovedItems;
+
+ // tree position
+ int treePosition;
};
QT_END_NAMESPACE
diff --git a/src/widgets/itemviews/qtreewidget.cpp b/src/widgets/itemviews/qtreewidget.cpp
index f72abd20ab..2de7830c6a 100644
--- a/src/widgets/itemviews/qtreewidget.cpp
+++ b/src/widgets/itemviews/qtreewidget.cpp
@@ -623,7 +623,13 @@ void QTreeModel::ensureSorted(int column, Qt::SortOrder order,
for (int i = 0; i < count; ++i) {
int oldRow = sorting.at(i).second;
+
+ int tmpitepos = lit - lst.begin();
QTreeWidgetItem *item = lst.takeAt(oldRow);
+ if (tmpitepos > lst.size())
+ --tmpitepos;
+ lit = lst.begin() + tmpitepos;
+
lit = sortedInsertionIterator(lit, lst.end(), order, item);
int newRow = qMax(lit - lst.begin(), 0);
diff --git a/src/widgets/kernel/qapplication.cpp b/src/widgets/kernel/qapplication.cpp
index b918bdb9e9..af3d134a5a 100644
--- a/src/widgets/kernel/qapplication.cpp
+++ b/src/widgets/kernel/qapplication.cpp
@@ -1852,8 +1852,11 @@ bool QApplication::event(QEvent *e)
if (showToolTip) {
QHelpEvent e(QEvent::ToolTip, d->toolTipPos, d->toolTipGlobalPos);
QApplication::sendEvent(d->toolTipWidget, &e);
- if (e.isAccepted())
- d->toolTipFallAsleep.start(2000, this);
+ if (e.isAccepted()) {
+ QStyle *s = d->toolTipWidget->style();
+ int sleepDelay = s->styleHint(QStyle::SH_ToolTip_FallAsleepDelay, 0, d->toolTipWidget, 0);
+ d->toolTipFallAsleep.start(sleepDelay, this);
+ }
}
}
} else if (te->timerId() == d->toolTipFallAsleep.timerId()) {
@@ -2949,12 +2952,8 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
QPoint relpos = mouse->pos();
if (e->spontaneous()) {
-
- if (e->type() == QEvent::MouseButtonPress) {
- QApplicationPrivate::giveFocusAccordingToFocusPolicy(w,
- Qt::ClickFocus,
- Qt::MouseFocusReason);
- }
+ if (e->type() != QEvent::MouseMove)
+ QApplicationPrivate::giveFocusAccordingToFocusPolicy(w, e, relpos);
// ### Qt 5 These dynamic tool tips should be an OPT-IN feature. Some platforms
// like Mac OS X (probably others too), can optimize their views by not
@@ -2967,7 +2966,9 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
d->toolTipWidget = w;
d->toolTipPos = relpos;
d->toolTipGlobalPos = mouse->globalPos();
- d->toolTipWakeUp.start(d->toolTipFallAsleep.isActive()?20:700, this);
+ QStyle *s = d->toolTipWidget->style();
+ int wakeDelay = s->styleHint(QStyle::SH_ToolTip_WakeUpDelay, 0, d->toolTipWidget, 0);
+ d->toolTipWakeUp.start(d->toolTipFallAsleep.isActive() ? 20 : wakeDelay, this);
}
}
@@ -3042,11 +3043,8 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
QPoint relpos = wheel->pos();
bool eventAccepted = wheel->isAccepted();
- if (e->spontaneous()) {
- QApplicationPrivate::giveFocusAccordingToFocusPolicy(w,
- Qt::WheelFocus,
- Qt::MouseFocusReason);
- }
+ if (e->spontaneous())
+ QApplicationPrivate::giveFocusAccordingToFocusPolicy(w, e, relpos);
while (w) {
QWheelEvent we(relpos, wheel->globalPos(), wheel->pixelDelta(), wheel->angleDelta(), wheel->delta(), wheel->orientation(), wheel->buttons(),
@@ -3234,6 +3232,11 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
QTouchEvent *touchEvent = static_cast<QTouchEvent *>(e);
const bool acceptTouchEvents = widget->testAttribute(Qt::WA_AcceptTouchEvents);
+ if (e->type() != QEvent::TouchUpdate && acceptTouchEvents && e->spontaneous()) {
+ const QPoint localPos = touchEvent->touchPoints()[0].pos().toPoint();
+ QApplicationPrivate::giveFocusAccordingToFocusPolicy(widget, e, localPos);
+ }
+
touchEvent->setTarget(widget);
touchEvent->setAccepted(acceptTouchEvents);
@@ -3251,16 +3254,16 @@ bool QApplication::notify(QObject *receiver, QEvent *e)
QWidget *widget = static_cast<QWidget *>(receiver);
QTouchEvent *touchEvent = static_cast<QTouchEvent *>(e);
bool eventAccepted = touchEvent->isAccepted();
- if (widget->testAttribute(Qt::WA_AcceptTouchEvents) && e->spontaneous()) {
- // give the widget focus if the focus policy allows it
- QApplicationPrivate::giveFocusAccordingToFocusPolicy(widget,
- Qt::ClickFocus,
- Qt::MouseFocusReason);
+ bool acceptTouchEvents = widget->testAttribute(Qt::WA_AcceptTouchEvents);
+
+ if (acceptTouchEvents && e->spontaneous()) {
+ const QPoint localPos = touchEvent->touchPoints()[0].pos().toPoint();
+ QApplicationPrivate::giveFocusAccordingToFocusPolicy(widget, e, localPos);
}
while (widget) {
// first, try to deliver the touch event
- bool acceptTouchEvents = widget->testAttribute(Qt::WA_AcceptTouchEvents);
+ acceptTouchEvents = widget->testAttribute(Qt::WA_AcceptTouchEvents);
touchEvent->setTarget(widget);
touchEvent->setAccepted(acceptTouchEvents);
QPointer<QWidget> p = widget;
@@ -3725,20 +3728,40 @@ bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event)
return QGuiApplication::sendSpontaneousEvent(receiver, event);
}
-
-void QApplicationPrivate::giveFocusAccordingToFocusPolicy(QWidget *widget,
- Qt::FocusPolicy focusPolicy,
- Qt::FocusReason focusReason)
+void QApplicationPrivate::giveFocusAccordingToFocusPolicy(QWidget *widget, QEvent *event, QPoint localPos)
{
+ const bool setFocusOnRelease = QGuiApplication::styleHints()->setFocusOnTouchRelease();
+ Qt::FocusPolicy focusPolicy = Qt::ClickFocus;
+
+ switch (event->type()) {
+ case QEvent::MouseButtonPress:
+ case QEvent::TouchBegin:
+ if (setFocusOnRelease)
+ return;
+ break;
+ case QEvent::MouseButtonRelease:
+ case QEvent::TouchEnd:
+ if (!setFocusOnRelease)
+ return;
+ break;
+ case QEvent::Wheel:
+ focusPolicy = Qt::WheelFocus;
+ break;
+ default:
+ return;
+ }
+
QWidget *focusWidget = widget;
while (focusWidget) {
if (focusWidget->isEnabled()
+ && focusWidget->rect().contains(localPos)
&& QApplicationPrivate::shouldSetFocus(focusWidget, focusPolicy)) {
- focusWidget->setFocus(focusReason);
+ focusWidget->setFocus(Qt::MouseFocusReason);
break;
}
if (focusWidget->isWindow())
break;
+ localPos += focusWidget->pos();
focusWidget = focusWidget->parentWidget();
}
}
diff --git a/src/widgets/kernel/qapplication_p.h b/src/widgets/kernel/qapplication_p.h
index 87cf259ba5..29c6902c78 100644
--- a/src/widgets/kernel/qapplication_p.h
+++ b/src/widgets/kernel/qapplication_p.h
@@ -294,9 +294,7 @@ public:
private:
static QApplicationPrivate *self;
- static void giveFocusAccordingToFocusPolicy(QWidget *w,
- Qt::FocusPolicy focusPolicy,
- Qt::FocusReason focusReason);
+ static void giveFocusAccordingToFocusPolicy(QWidget *w, QEvent *event, QPoint localPos);
static bool shouldSetFocus(QWidget *w, Qt::FocusPolicy policy);
diff --git a/src/widgets/kernel/qapplication_qpa.cpp b/src/widgets/kernel/qapplication_qpa.cpp
index 852b6b9697..0fc065e74b 100644
--- a/src/widgets/kernel/qapplication_qpa.cpp
+++ b/src/widgets/kernel/qapplication_qpa.cpp
@@ -198,7 +198,6 @@ void QApplicationPrivate::closePopup(QWidget *popup)
// mouse release event or inside
qt_replay_popup_mouse_event = false;
} else { // mouse press event
- QGuiApplicationPrivate::mousePressTime -= 10000; // avoid double click
qt_replay_popup_mouse_event = true;
}
diff --git a/src/widgets/kernel/qlayout.cpp b/src/widgets/kernel/qlayout.cpp
index a65c34adf5..8541dd984d 100644
--- a/src/widgets/kernel/qlayout.cpp
+++ b/src/widgets/kernel/qlayout.cpp
@@ -1443,7 +1443,7 @@ QDataStream &operator<<(QDataStream &stream, const QSizePolicy &policy)
policy.bits.hfw << 8 | // [8]
policy.bits.ctype << 9 | // [9, 13]
policy.bits.wfh << 14 | // [14]
- //policy.bits.padding << 15 | // [15]
+ policy.bits.retainSizeWhenHidden << 15 | // [15]
policy.bits.verStretch << 16 | // [16, 23]
policy.bits.horStretch << 24); // [24, 31]
return stream << data;
@@ -1468,7 +1468,7 @@ QDataStream &operator>>(QDataStream &stream, QSizePolicy &policy)
policy.bits.hfw = VALUE_OF_BITS(data, 8, 1);
policy.bits.ctype = VALUE_OF_BITS(data, 9, 5);
policy.bits.wfh = VALUE_OF_BITS(data, 14, 1);
- policy.bits.padding = 0;
+ policy.bits.retainSizeWhenHidden = VALUE_OF_BITS(data, 15, 1);
policy.bits.verStretch = VALUE_OF_BITS(data, 16, 8);
policy.bits.horStretch = VALUE_OF_BITS(data, 24, 8);
return stream;
diff --git a/src/widgets/kernel/qlayoutitem.cpp b/src/widgets/kernel/qlayoutitem.cpp
index 223bcf1d9b..a99ea77ce2 100644
--- a/src/widgets/kernel/qlayoutitem.cpp
+++ b/src/widgets/kernel/qlayoutitem.cpp
@@ -682,7 +682,7 @@ bool QSpacerItem::isEmpty() const
*/
bool QWidgetItem::isEmpty() const
{
- return wid->isHidden() || wid->isWindow();
+ return (wid->isHidden() && !wid->sizePolicy().retainSizeWhenHidden()) || wid->isWindow();
}
/*!
diff --git a/src/widgets/kernel/qsizepolicy.h b/src/widgets/kernel/qsizepolicy.h
index 2fe85cbe0c..9c6d67410a 100644
--- a/src/widgets/kernel/qsizepolicy.h
+++ b/src/widgets/kernel/qsizepolicy.h
@@ -131,6 +131,9 @@ public:
void setHorizontalStretch(int stretchFactor) { bits.horStretch = static_cast<quint32>(qBound(0, stretchFactor, 255)); }
void setVerticalStretch(int stretchFactor) { bits.verStretch = static_cast<quint32>(qBound(0, stretchFactor, 255)); }
+ bool retainSizeWhenHidden() const { return bits.retainSizeWhenHidden; }
+ void setRetainSizeWhenHidden(bool retainSize) { bits.retainSizeWhenHidden = retainSize; }
+
void transpose();
@@ -150,7 +153,7 @@ private:
quint32 ctype : 5;
quint32 hfw : 1;
quint32 wfh : 1;
- quint32 padding : 1; // feel free to use
+ quint32 retainSizeWhenHidden : 1;
} bits;
quint32 data;
};
diff --git a/src/widgets/kernel/qsizepolicy.qdoc b/src/widgets/kernel/qsizepolicy.qdoc
index 6af694d999..2c088113e1 100644
--- a/src/widgets/kernel/qsizepolicy.qdoc
+++ b/src/widgets/kernel/qsizepolicy.qdoc
@@ -341,6 +341,23 @@
*/
/*!
+ \fn void QSizePolicy::retainSizeWhenHidden() const
+
+ Returns if the layout should retain the widgets size when it is hidden. This is by default false.
+
+ \sa setRetainSizeWhenHidden()
+*/
+
+/*!
+ \fn void QSizePolicy::setRetainSizeWhenHidden(bool retainSize)
+
+ Set if a layout should retain the widgets size when it is hidden.
+ If \a retainSize is true the layout will not be changed by hiding the widget.
+
+ \sa retainSizeWhenHidden()
+*/
+
+/*!
\enum QSizePolicy::ControlType
\since 4.3
diff --git a/src/widgets/kernel/qtooltip.cpp b/src/widgets/kernel/qtooltip.cpp
index 864ed6a555..8399f94976 100644
--- a/src/widgets/kernel/qtooltip.cpp
+++ b/src/widgets/kernel/qtooltip.cpp
@@ -120,7 +120,7 @@ class QTipLabel : public QLabel
{
Q_OBJECT
public:
- QTipLabel(const QString &text, QWidget *w);
+ QTipLabel(const QString &text, QWidget *w, int msecDisplayTime);
~QTipLabel();
static QTipLabel *instance;
@@ -130,11 +130,11 @@ public:
bool fadingOut;
- void reuseTip(const QString &text);
+ void reuseTip(const QString &text, int msecDisplayTime);
void hideTip();
void hideTipImmediately();
void setTipRect(QWidget *w, const QRect &r);
- void restartExpireTimer();
+ void restartExpireTimer(int msecDisplayTime);
bool tipChanged(const QPoint &pos, const QString &text, QObject *o);
void placeTip(const QPoint &pos, QWidget *w);
@@ -166,7 +166,7 @@ private:
QTipLabel *QTipLabel::instance = 0;
-QTipLabel::QTipLabel(const QString &text, QWidget *w)
+QTipLabel::QTipLabel(const QString &text, QWidget *w, int msecDisplayTime)
#ifndef QT_NO_STYLE_STYLESHEET
: QLabel(w, Qt::ToolTip | Qt::BypassGraphicsProxyWidget), styleSheetParent(0), widget(0)
#else
@@ -187,17 +187,19 @@ QTipLabel::QTipLabel(const QString &text, QWidget *w)
setWindowOpacity(style()->styleHint(QStyle::SH_ToolTipLabel_Opacity, 0, this) / 255.0);
setMouseTracking(true);
fadingOut = false;
- reuseTip(text);
+ reuseTip(text, msecDisplayTime);
}
-void QTipLabel::restartExpireTimer()
+void QTipLabel::restartExpireTimer(int msecDisplayTime)
{
int time = 10000 + 40 * qMax(0, text().length()-100);
+ if (msecDisplayTime > 0)
+ time = msecDisplayTime;
expireTimer.start(time, this);
hideTimer.stop();
}
-void QTipLabel::reuseTip(const QString &text)
+void QTipLabel::reuseTip(const QString &text, int msecDisplayTime)
{
#ifndef QT_NO_STYLE_STYLESHEET
if (styleSheetParent){
@@ -215,7 +217,7 @@ void QTipLabel::reuseTip(const QString &text)
if (fm.descent() == 2 && fm.ascent() >= 11)
++extra.rheight();
resize(sizeHint() + extra);
- restartExpireTimer();
+ restartExpireTimer(msecDisplayTime);
}
void QTipLabel::paintEvent(QPaintEvent *ev)
@@ -440,6 +442,18 @@ bool QTipLabel::tipChanged(const QPoint &pos, const QString &text, QObject *o)
void QToolTip::showText(const QPoint &pos, const QString &text, QWidget *w, const QRect &rect)
{
+ showText(pos, text, w, rect, -1);
+}
+
+/*!
+ \since 5.2
+ \overload
+ This is similar to QToolTip::showText(\a pos, \a text, \a w, \a rect) but with an extra parameter \a msecDisplayTime
+ that specifies how long the tool tip will be displayed, in milliseconds.
+*/
+
+void QToolTip::showText(const QPoint &pos, const QString &text, QWidget *w, const QRect &rect, int msecDisplayTime)
+{
if (QTipLabel::instance && QTipLabel::instance->isVisible()){ // a tip does already exist
if (text.isEmpty()){ // empty text means hide current tip
QTipLabel::instance->hideTip();
@@ -452,7 +466,7 @@ void QToolTip::showText(const QPoint &pos, const QString &text, QWidget *w, cons
if (w)
localPos = w->mapFromGlobal(pos);
if (QTipLabel::instance->tipChanged(localPos, text, w)){
- QTipLabel::instance->reuseTip(text);
+ QTipLabel::instance->reuseTip(text, msecDisplayTime);
QTipLabel::instance->setTipRect(w, rect);
QTipLabel::instance->placeTip(pos, w);
}
@@ -462,11 +476,11 @@ void QToolTip::showText(const QPoint &pos, const QString &text, QWidget *w, cons
if (!text.isEmpty()){ // no tip can be reused, create new tip:
#ifndef Q_WS_WIN
- new QTipLabel(text, w); // sets QTipLabel::instance to itself
+ new QTipLabel(text, w, msecDisplayTime); // sets QTipLabel::instance to itself
#else
// On windows, we can't use the widget as parent otherwise the window will be
// raised when the tooltip will be shown
- new QTipLabel(text, QApplication::desktop()->screen(QTipLabel::getTipScreen(pos, w)));
+ new QTipLabel(text, QApplication::desktop()->screen(QTipLabel::getTipScreen(pos, w)), msecDisplayTime);
#endif
QTipLabel::instance->setTipRect(w, rect);
QTipLabel::instance->placeTip(pos, w);
diff --git a/src/widgets/kernel/qtooltip.h b/src/widgets/kernel/qtooltip.h
index 25b138b855..ccde405342 100644
--- a/src/widgets/kernel/qtooltip.h
+++ b/src/widgets/kernel/qtooltip.h
@@ -53,8 +53,10 @@ class Q_WIDGETS_EXPORT QToolTip
{
QToolTip() Q_DECL_EQ_DELETE;
public:
+ // ### Qt 6 - merge the three showText functions below
static void showText(const QPoint &pos, const QString &text, QWidget *w = 0);
static void showText(const QPoint &pos, const QString &text, QWidget *w, const QRect &rect);
+ static void showText(const QPoint &pos, const QString &text, QWidget *w, const QRect &rect, int msecShowTime);
static inline void hideText() { showText(QPoint(), QString()); }
static bool isVisible();
diff --git a/src/widgets/kernel/qwidget.cpp b/src/widgets/kernel/qwidget.cpp
index 49d64c5cd8..5532b04b22 100644
--- a/src/widgets/kernel/qwidget.cpp
+++ b/src/widgets/kernel/qwidget.cpp
@@ -245,6 +245,9 @@ QWidgetPrivate::QWidgetPrivate(int version)
#if !defined(QT_NO_IM)
, imHints(Qt::ImhNone)
#endif
+#ifndef QT_NO_TOOLTIP
+ , toolTipDuration(-1)
+#endif
, inheritedFontResolveMask(0)
, inheritedPaletteResolveMask(0)
, leftmargin(0)
@@ -261,6 +264,7 @@ QWidgetPrivate::QWidgetPrivate(int version)
, bg_role(QPalette::NoRole)
, dirtyOpaqueChildren(1)
, isOpaque(0)
+ , retainSizeWhenHiddenChanged(0)
, inDirtyList(0)
, isScrolled(0)
, isMoved(0)
@@ -7264,10 +7268,19 @@ void QWidget::setVisible(bool visible)
create();
}
-#if defined(Q_WS_X11)
- if (windowType() == Qt::Window)
- QApplicationPrivate::applyX11SpecificCommandLineArguments(this);
-#endif
+ // Handling of the -qwindowgeometry, -geometry command line arguments
+ if (windowType() == Qt::Window && windowHandle()) {
+ static bool done = false;
+ if (!done) {
+ done = true;
+ const QRect oldGeometry = frameGeometry();
+ const QRect geometry = QGuiApplicationPrivate::applyWindowGeometrySpecification(oldGeometry, windowHandle());
+ if (oldGeometry.size() != geometry.size())
+ resize(geometry.size());
+ if (geometry.topLeft() != oldGeometry.topLeft())
+ move(geometry.topLeft());
+ } // done
+ }
bool wasResized = testAttribute(Qt::WA_Resized);
Qt::WindowStates initialWindowState = windowState();
@@ -8207,7 +8220,7 @@ bool QWidget::event(QEvent *event)
#ifndef QT_NO_TOOLTIP
case QEvent::ToolTip:
if (!d->toolTip.isEmpty())
- QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), d->toolTip, this);
+ QToolTip::showText(static_cast<QHelpEvent*>(event)->globalPos(), d->toolTip, this, QRect(), d->toolTipDuration);
else
event->ignore();
break;
@@ -9251,6 +9264,10 @@ void QWidget::setSizePolicy(QSizePolicy policy)
setAttribute(Qt::WA_WState_OwnSizePolicy);
if (policy == d->size_policy)
return;
+
+ if (d->size_policy.retainSizeWhenHidden() != policy.retainSizeWhenHidden())
+ d->retainSizeWhenHiddenChanged = 1;
+
d->size_policy = policy;
#ifndef QT_NO_GRAPHICSVIEW
@@ -9261,6 +9278,7 @@ void QWidget::setSizePolicy(QSizePolicy policy)
#endif
updateGeometry();
+ d->retainSizeWhenHiddenChanged = 0;
if (isWindow() && d->maybeTopData())
d->topData()->sizeAdjusted = false;
@@ -9389,7 +9407,9 @@ void QWidgetPrivate::updateGeometry_helper(bool forceUpdate)
widgetItem->invalidateSizeCache();
QWidget *parent;
if (forceUpdate || !extra || extra->minw != extra->maxw || extra->minh != extra->maxh) {
- if (!q->isWindow() && !q->isHidden() && (parent = q->parentWidget())) {
+ const int isHidden = q->isHidden() && !size_policy.retainSizeWhenHidden() && !retainSizeWhenHiddenChanged;
+
+ if (!q->isWindow() && !isHidden && (parent = q->parentWidget())) {
if (parent->d_func()->layout)
parent->d_func()->layout->invalidate();
else if (parent->isVisible())
@@ -10019,6 +10039,13 @@ void QWidget::setAttribute(Qt::WidgetAttribute attribute, bool on)
}
#endif
+ // Don't set WA_NativeWindow on platforms that don't support it
+ if (attribute == Qt::WA_NativeWindow) {
+ QPlatformIntegration *platformIntegration = QGuiApplicationPrivate::platformIntegration();
+ if (!platformIntegration->hasCapability(QPlatformIntegration::NativeWidgets))
+ return;
+ }
+
setAttribute_internal(attribute, on, data, d);
switch (attribute) {
@@ -10426,6 +10453,30 @@ QString QWidget::toolTip() const
Q_D(const QWidget);
return d->toolTip;
}
+
+/*!
+ \property QWidget::toolTipDuration
+ \brief the widget's tooltip duration
+ \since 5.2
+
+ Specifies how long time the tooltip will be displayed, in milliseconds.
+ If the value is -1 (default) the duration is calculated depending on the length of the tooltip.
+
+ \sa toolTip
+*/
+
+void QWidget::setToolTipDuration(int msec)
+{
+ Q_D(QWidget);
+ d->toolTipDuration = msec;
+}
+
+int QWidget::toolTipDuration() const
+{
+ Q_D(const QWidget);
+ return d->toolTipDuration;
+}
+
#endif // QT_NO_TOOLTIP
diff --git a/src/widgets/kernel/qwidget.h b/src/widgets/kernel/qwidget.h
index f90f2ee5f5..f579dbb9cd 100644
--- a/src/widgets/kernel/qwidget.h
+++ b/src/widgets/kernel/qwidget.h
@@ -178,6 +178,7 @@ class Q_WIDGETS_EXPORT QWidget : public QObject, public QPaintDevice
Q_PROPERTY(bool windowModified READ isWindowModified WRITE setWindowModified DESIGNABLE isWindow)
#ifndef QT_NO_TOOLTIP
Q_PROPERTY(QString toolTip READ toolTip WRITE setToolTip)
+ Q_PROPERTY(int toolTipDuration READ toolTipDuration WRITE setToolTipDuration)
#endif
#ifndef QT_NO_STATUSTIP
Q_PROPERTY(QString statusTip READ statusTip WRITE setStatusTip)
@@ -376,6 +377,8 @@ public:
#ifndef QT_NO_TOOLTIP
void setToolTip(const QString &);
QString toolTip() const;
+ void setToolTipDuration(int msec);
+ int toolTipDuration() const;
#endif
#ifndef QT_NO_STATUSTIP
void setStatusTip(const QString &);
diff --git a/src/widgets/kernel/qwidget_p.h b/src/widgets/kernel/qwidget_p.h
index 50f32af8b0..0580f72e11 100644
--- a/src/widgets/kernel/qwidget_p.h
+++ b/src/widgets/kernel/qwidget_p.h
@@ -644,6 +644,7 @@ public:
QRegion dirty;
#ifndef QT_NO_TOOLTIP
QString toolTip;
+ int toolTipDuration;
#endif
#ifndef QT_NO_STATUSTIP
QString statusTip;
@@ -687,6 +688,7 @@ public:
QPalette::ColorRole bg_role : 8;
uint dirtyOpaqueChildren : 1;
uint isOpaque : 1;
+ uint retainSizeWhenHiddenChanged : 1;
uint inDirtyList : 1;
uint isScrolled : 1;
uint isMoved : 1;
diff --git a/src/widgets/kernel/qwidgetwindow.cpp b/src/widgets/kernel/qwidgetwindow.cpp
index 675ea77b30..f2bd389769 100644
--- a/src/widgets/kernel/qwidgetwindow.cpp
+++ b/src/widgets/kernel/qwidgetwindow.cpp
@@ -559,7 +559,7 @@ void QWidgetWindow::handleWheelEvent(QWheelEvent *event)
QPoint mapped = widget->mapFrom(m_widget, event->pos());
- QWheelEvent translated(mapped, event->globalPos(), event->pixelDelta(), event->angleDelta(), event->delta(), event->orientation(), event->buttons(), event->modifiers());
+ QWheelEvent translated(mapped, event->globalPos(), event->pixelDelta(), event->angleDelta(), event->delta(), event->orientation(), event->buttons(), event->modifiers(), event->phase());
QGuiApplication::sendSpontaneousEvent(widget, &translated);
}
diff --git a/src/widgets/styles/images/cleartext-16.png b/src/widgets/styles/images/cleartext-16.png
new file mode 100644
index 0000000000..74133bafff
--- /dev/null
+++ b/src/widgets/styles/images/cleartext-16.png
Binary files differ
diff --git a/src/widgets/styles/qcommonstyle.cpp b/src/widgets/styles/qcommonstyle.cpp
index ba6c222820..539cc70eb7 100644
--- a/src/widgets/styles/qcommonstyle.cpp
+++ b/src/widgets/styles/qcommonstyle.cpp
@@ -65,6 +65,7 @@
#include <qtoolbar.h>
#include <qtoolbutton.h>
#include <qrubberband.h>
+#include "qtreeview.h"
#include <private/qcommonstylepixmaps_p.h>
#include <private/qmath_p.h>
#include <qdebug.h>
@@ -5096,11 +5097,7 @@ int QCommonStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget
ret = theme->themeHint(QPlatformTheme::ToolButtonStyle).toInt();
break;
case SH_RequestSoftwareInputPanel:
-#ifdef Q_OS_ANDROID
ret = RSIP_OnMouseClick;
-#else
- ret = RSIP_OnMouseClickAndAlreadyFocused;
-#endif
break;
case SH_ScrollBar_Transient:
ret = false;
@@ -5108,6 +5105,27 @@ int QCommonStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget
case SH_Menu_SupportsSections:
ret = false;
break;
+#ifndef QT_NO_TOOLTIP
+ case SH_ToolTip_WakeUpDelay:
+ ret = 700;
+ break;
+ case SH_ToolTip_FallAsleepDelay:
+ ret = 2000;
+ break;
+#endif
+ case SH_Widget_Animate:
+#ifndef QT_NO_TREEVIEW
+ if (qobject_cast<const QTreeView*>(widget)) {
+ ret = false;
+ } else
+#endif
+ {
+ ret = true;
+ }
+ break;
+ case SH_Splitter_OpaqueResize:
+ ret = true;
+ break;
default:
ret = 0;
break;
@@ -5288,6 +5306,13 @@ QPixmap QCommonStyle::standardPixmap(StandardPixmap sp, const QStyleOption *opti
}
}
break;
+ case SP_LineEditClearButton: {
+ QString themeName = rtl ? QStringLiteral("edit-clear-locationbar-ltr") : QStringLiteral("edit-clear-locationbar-rtl");
+ if (!QIcon::hasThemeIcon(themeName))
+ themeName = QStringLiteral("edit-clear");
+ pixmap = QIcon::fromTheme(themeName).pixmap(16);
+ }
+ break;
default:
break;
}
@@ -5416,6 +5441,8 @@ QPixmap QCommonStyle::standardPixmap(StandardPixmap sp, const QStyleOption *opti
return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-volume-16.png"));
case SP_MediaVolumeMuted:
return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/media-volume-muted-16.png"));
+ case SP_LineEditClearButton:
+ return QPixmap(QStringLiteral(":/qt-project.org/styles/commonstyle/images/cleartext-16.png"));
#endif // QT_NO_IMAGEFORMAT_PNG
default:
break;
diff --git a/src/widgets/styles/qgtkstyle_p.cpp b/src/widgets/styles/qgtkstyle_p.cpp
index 769d822108..c53a21e59a 100644
--- a/src/widgets/styles/qgtkstyle_p.cpp
+++ b/src/widgets/styles/qgtkstyle_p.cpp
@@ -756,8 +756,9 @@ void QGtkStylePrivate::removeWidgetFromMap(const QHashableLatin1Literal &path)
WidgetMap *map = gtkWidgetMap();
WidgetMap::iterator it = map->find(path);
if (it != map->end()) {
- free(const_cast<char *>(it.key().data()));
+ char* keyData = const_cast<char *>(it.key().data());
map->erase(it);
+ free(keyData);
}
}
diff --git a/src/widgets/styles/qstyle.cpp b/src/widgets/styles/qstyle.cpp
index dccc9ff3ce..99bbf2f363 100644
--- a/src/widgets/styles/qstyle.cpp
+++ b/src/widgets/styles/qstyle.cpp
@@ -1894,6 +1894,19 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
\value SH_Menu_SupportsSections Determines if the style displays sections in menus or treat them as
plain separators. Sections are separators with a text and icon hint.
+ \value SH_ToolTip_WakeUpDelay Determines the delay before a tooltip is shown, in milliseconds.
+
+ \value SH_ToolTip_FallAsleepDelay Determines the delay (in milliseconds) before a new wake time is needed when
+ a tooltip is shown (notice: shown, not hidden). When a new wake isn't needed, a user-requested tooltip
+ will be shown nearly instantly.
+
+ \value SH_Widget_Animate Determines if the widget should show animations or not, for example
+ a transition between checked and unchecked statuses in a checkbox.
+ This enum value has been introduced in Qt 5.2.
+
+ \value SH_Splitter_OpaqueResize Determines if resizing is opaque
+ This enum value has been introduced in Qt 5.2
+
\sa styleHint()
*/
@@ -1986,6 +1999,7 @@ void QStyle::drawItemPixmap(QPainter *painter, const QRect &rect, int alignment,
\value SP_MediaSeekBackward Icon indicating that media should seek backward.
\value SP_MediaVolume Icon indicating a volume control.
\value SP_MediaVolumeMuted Icon indicating a muted volume control.
+ \value SP_LineEditClearButton Icon for a standard clear button in a QLineEdit. This enum value was added in Qt 5.2.
\value SP_CustomBase Base value for custom standard pixmaps;
custom values must be greater than this value.
diff --git a/src/widgets/styles/qstyle.h b/src/widgets/styles/qstyle.h
index beafad326e..bbb216bf92 100644
--- a/src/widgets/styles/qstyle.h
+++ b/src/widgets/styles/qstyle.h
@@ -698,6 +698,10 @@ public:
SH_RequestSoftwareInputPanel,
SH_ScrollBar_Transient,
SH_Menu_SupportsSections,
+ SH_ToolTip_WakeUpDelay,
+ SH_ToolTip_FallAsleepDelay,
+ SH_Widget_Animate,
+ SH_Splitter_OpaqueResize,
// Add new style hint values here
SH_CustomBase = 0xf0000000
@@ -777,6 +781,7 @@ public:
SP_MediaSeekBackward,
SP_MediaVolume,
SP_MediaVolumeMuted,
+ SP_LineEditClearButton,
// do not add any values below/greater than this
SP_CustomBase = 0xf0000000
};
diff --git a/src/widgets/styles/qstyle.qrc b/src/widgets/styles/qstyle.qrc
index 28ad484032..c063ec5036 100644
--- a/src/widgets/styles/qstyle.qrc
+++ b/src/widgets/styles/qstyle.qrc
@@ -1,5 +1,6 @@
<RCC>
<qresource prefix="/qt-project.org/styles/commonstyle">
+ <file>images/cleartext-16.png</file>
<file>images/filelink-16.png</file>
<file>images/filelink-32.png</file>
<file>images/filelink-128.png</file>
diff --git a/src/widgets/util/qsystemtrayicon_x11.cpp b/src/widgets/util/qsystemtrayicon_x11.cpp
index 5204b85a9a..347e5701c0 100644
--- a/src/widgets/util/qsystemtrayicon_x11.cpp
+++ b/src/widgets/util/qsystemtrayicon_x11.cpp
@@ -57,84 +57,19 @@
#include <qpa/qplatformnativeinterface.h>
#include <qdebug.h>
-#include <X11/Xlib.h>
-#include <X11/Xutil.h>
-#include <X11/Xos.h>
-#include <X11/Xatom.h>
-
#ifndef QT_NO_SYSTEMTRAYICON
QT_BEGIN_NAMESPACE
-enum {
- SYSTEM_TRAY_REQUEST_DOCK = 0,
- SYSTEM_TRAY_BEGIN_MESSAGE = 1,
- SYSTEM_TRAY_CANCEL_MESSAGE =2
-};
-
-// ### fixme (15.3.2012): The following issues need to be resolved:
-// - Tracking of the actual tray window for DestroyNotify and re-creation
-// of the icons on the new window should it change (see Qt 4.X).
-
-// Global context for the X11 system tray containing a display for the primary
-// screen and a selection atom from which the tray window can be determined.
-class QX11SystemTrayContext
-{
-public:
- QX11SystemTrayContext();
- ~QX11SystemTrayContext();
-
- bool isValid() const { return m_systemTraySelection != 0; }
-
- inline Display *display() const { return m_display; }
- inline int screenNumber() const { return m_screenNumber; }
- Window locateSystemTray() const;
-
-private:
- Display *m_display;
- int m_screenNumber;
- Atom m_systemTraySelection;
-};
-
-QX11SystemTrayContext::QX11SystemTrayContext() : m_display(0), m_screenNumber(0), m_systemTraySelection(0)
-{
- QScreen *screen = QGuiApplication::primaryScreen();
- if (!screen) {
- qWarning("%s: No screen.", Q_FUNC_INFO);
- return;
- }
- void *displayV = QGuiApplication::platformNativeInterface()->nativeResourceForScreen(QByteArrayLiteral("display"), screen);
- if (!displayV) {
- qWarning("%s: Unable to obtain X11 display of primary screen.", Q_FUNC_INFO);
- return;
- }
-
- m_display = static_cast<Display *>(displayV);
-
- const QByteArray netSysTray = "_NET_SYSTEM_TRAY_S" + QByteArray::number(m_screenNumber);
- m_systemTraySelection = XInternAtom(m_display, netSysTray.constData(), False);
- if (!m_systemTraySelection) {
- qWarning("%s: Unable to retrieve atom '%s'.", Q_FUNC_INFO, netSysTray.constData());
- return;
- }
-}
-
-Window QX11SystemTrayContext::locateSystemTray() const
+static inline unsigned long locateSystemTray()
{
- if (isValid())
- return XGetSelectionOwner(m_display, m_systemTraySelection);
- return 0;
+ return (unsigned long)QGuiApplication::platformNativeInterface()->nativeResourceForScreen(QByteArrayLiteral("traywindow"), QGuiApplication::primaryScreen());
}
-QX11SystemTrayContext::~QX11SystemTrayContext()
-{
-}
-
-Q_GLOBAL_STATIC(QX11SystemTrayContext, qX11SystemTrayContext)
-
// System tray widget. Could be replaced by a QWindow with
// a backing store if it did not need tooltip handling.
class QSystemTrayIconSys : public QWidget
{
+ Q_OBJECT
public:
explicit QSystemTrayIconSys(QSystemTrayIcon *q);
@@ -149,7 +84,12 @@ protected:
virtual bool event(QEvent *);
virtual void paintEvent(QPaintEvent *);
+private slots:
+ void systemTrayWindowChanged(QScreen *screen);
+
private:
+ bool addToTray();
+
QSystemTrayIcon *q;
};
@@ -159,47 +99,59 @@ QSystemTrayIconSys::QSystemTrayIconSys(QSystemTrayIcon *qIn)
{
setObjectName(QStringLiteral("QSystemTrayIconSys"));
setToolTip(q->toolTip());
- QX11SystemTrayContext *context = qX11SystemTrayContext();
- Q_ASSERT(context->isValid());
setAttribute(Qt::WA_AlwaysShowToolTips, true);
setAttribute(Qt::WA_TranslucentBackground, true);
setAttribute(Qt::WA_QuitOnClose, false);
const QSize size(22, 22); // Gnome, standard size
setGeometry(QRect(QPoint(0, 0), size));
setMinimumSize(size);
+ addToTray();
+}
+
+bool QSystemTrayIconSys::addToTray()
+{
+ if (!locateSystemTray())
+ return false;
+
createWinId();
setMouseTracking(true);
- Display *display = context->display();
-
- // Request to be a tray window according to GNOME, NET WM Specification
- static Atom netwm_tray_atom = XInternAtom(display, "_NET_SYSTEM_TRAY_OPCODE", False);
- long l[5] = { CurrentTime, SYSTEM_TRAY_REQUEST_DOCK, static_cast<long>(winId()), 0, 0 };
- XEvent ev;
- memset(&ev, 0, sizeof(ev));
- ev.xclient.type = ClientMessage;
- ev.xclient.window = context->locateSystemTray();
- ev.xclient.message_type = netwm_tray_atom;
- ev.xclient.format = 32;
- memcpy((char *)&ev.xclient.data, (const char *) l, sizeof(l));
- XSendEvent(display, ev.xclient.window, False, 0, &ev);
+ bool requestResult = false;
+ if (!QMetaObject::invokeMethod(QGuiApplication::platformNativeInterface(),
+ "requestSystemTrayWindowDock", Qt::DirectConnection,
+ Q_RETURN_ARG(bool, requestResult),
+ Q_ARG(const QWindow *, windowHandle()))
+ || !requestResult) {
+ qWarning("requestSystemTrayWindowDock failed.");
+ return false;
+ }
show();
+ return true;
}
-QRect QSystemTrayIconSys::globalGeometry() const
+void QSystemTrayIconSys::systemTrayWindowChanged(QScreen *)
{
- QX11SystemTrayContext *context = qX11SystemTrayContext();
- ::Window dummy;
- int x, y, rootX, rootY;
- unsigned int width, height, border, depth;
- // Use X11 API since we are parented on the tray, about which the QWindow does not know.
- XGetGeometry(context->display(), winId(), &dummy, &x, &y, &width, &height, &border, &depth);
- XTranslateCoordinates(context->display(), winId(),
- XRootWindow(context->display(), context->screenNumber()),
- x, y, &rootX, &rootY, &dummy);
- return QRect(QPoint(rootX, rootY), QSize(width, height));
+ if (locateSystemTray()) {
+ addToTray();
+ } else {
+ QBalloonTip::hideBalloon();
+ hide(); // still no luck
+ destroy();
+ }
}
+QRect QSystemTrayIconSys::globalGeometry() const
+{
+ QRect result;
+ if (!QMetaObject::invokeMethod(QGuiApplication::platformNativeInterface(),
+ "systemTrayWindowGlobalGeometry", Qt::DirectConnection,
+ Q_RETURN_ARG(QRect, result),
+ Q_ARG(const QWindow *, windowHandle()))
+ || !result.isValid()) {
+ qWarning("systemTrayWindowGlobalGeometry failed.");
+ }
+ return result;
+}
void QSystemTrayIconSys::mousePressEvent(QMouseEvent *ev)
{
@@ -268,8 +220,11 @@ QSystemTrayIconPrivate::~QSystemTrayIconPrivate()
void QSystemTrayIconPrivate::install_sys()
{
Q_Q(QSystemTrayIcon);
- if (!sys && qX11SystemTrayContext()->isValid())
+ if (!sys && locateSystemTray()) {
sys = new QSystemTrayIconSys(q);
+ QObject::connect(QGuiApplication::platformNativeInterface(), SIGNAL(systemTrayWindowChanged(QScreen*)),
+ sys, SLOT(systemTrayWindowChanged(QScreen*)));
+ }
}
QRect QSystemTrayIconPrivate::geometry_sys() const
@@ -313,7 +268,7 @@ bool QSystemTrayIconPrivate::isSystemTrayAvailable_sys()
{
const QString platform = QGuiApplication::platformName();
if (platform.compare(QStringLiteral("xcb"), Qt::CaseInsensitive) == 0)
- return qX11SystemTrayContext()->locateSystemTray() != None;
+ return locateSystemTray();
return false;
}
@@ -334,4 +289,7 @@ void QSystemTrayIconPrivate::showMessage_sys(const QString &message, const QStri
}
QT_END_NAMESPACE
+
+#include "qsystemtrayicon_x11.moc"
+
#endif //QT_NO_SYSTEMTRAYICON
diff --git a/src/widgets/util/util.pri b/src/widgets/util/util.pri
index 598a3082c0..072c736f71 100644
--- a/src/widgets/util/util.pri
+++ b/src/widgets/util/util.pri
@@ -31,7 +31,6 @@ win32:!wince* {
SOURCES += util/qsystemtrayicon_win.cpp
} else:contains(QT_CONFIG, xcb) {
SOURCES += util/qsystemtrayicon_x11.cpp
- CONFIG += x11
} else {
SOURCES += util/qsystemtrayicon_qpa.cpp
}
diff --git a/src/widgets/widgets/qabstractscrollarea.cpp b/src/widgets/widgets/qabstractscrollarea.cpp
index 900e95f4da..e7827055fb 100644
--- a/src/widgets/widgets/qabstractscrollarea.cpp
+++ b/src/widgets/widgets/qabstractscrollarea.cpp
@@ -167,6 +167,7 @@ QT_BEGIN_NAMESPACE
QAbstractScrollAreaPrivate::QAbstractScrollAreaPrivate()
:hbar(0), vbar(0), vbarpolicy(Qt::ScrollBarAsNeeded), hbarpolicy(Qt::ScrollBarAsNeeded),
+ shownOnce(false), sizeAdjustPolicy(QAbstractScrollArea::AdjustIgnored),
viewport(0), cornerWidget(0), left(0), top(0), right(0), bottom(0),
xoffset(0), yoffset(0), viewportFilter(0)
#ifdef Q_WS_WIN
@@ -527,6 +528,19 @@ void QAbstractScrollAreaPrivate::layoutChildren()
}
/*!
+ \enum QAbstractScrollArea::SizeAdjustPolicy
+ \since 5.2
+
+ This enum specifies how the size hint of the QAbstractScrollArea should
+ adjust when the size of the viewport changes.
+
+ \value AdjustIgnored The scroll area will behave like before - and not do any adjust.
+ \value AdjustToContents The scroll area will always adjust to the viewport
+ \value AdjustToContentsOnFirstShow The scroll area will adjust to its viewport the first time it is shown.
+*/
+
+
+/*!
\internal
Creates a new QAbstractScrollAreaPrivate, \a dd with the given \a parent.
@@ -983,6 +997,13 @@ bool QAbstractScrollArea::event(QEvent *e)
case QEvent::Resize:
d->layoutChildren();
break;
+ case QEvent::Show:
+ if (!d->shownOnce && d->sizeAdjustPolicy == QAbstractScrollArea::AdjustToContentsOnFirstShow) {
+ d->sizeHint = QSize();
+ updateGeometry();
+ }
+ d->shownOnce = true;
+ return QFrame::event(e);
case QEvent::Paint: {
QStyleOption option;
option.initFrom(this);
@@ -1533,17 +1554,70 @@ QSize QAbstractScrollArea::minimumSizeHint() const
}
/*!
+ Returns the sizeHint property of the scroll area. The size is determined by using
+ viewportSizeHint() plus some extra space for scroll bars, if needed.
\reimp
*/
QSize QAbstractScrollArea::sizeHint() const
{
- return QSize(256, 192);
-#if 0
Q_D(const QAbstractScrollArea);
- int h = qMax(10, fontMetrics().height());
- int f = 2 * d->frameWidth;
- return QSize((6 * h) + f, (4 * h) + f);
-#endif
+ if (d->sizeAdjustPolicy == QAbstractScrollArea::AdjustIgnored)
+ return QSize(256, 192);
+
+ if (!d->sizeHint.isValid() || d->sizeAdjustPolicy == QAbstractScrollArea::AdjustToContents) {
+ const int f = 2 * d->frameWidth;
+ const QSize frame( f, f );
+ const QSize scrollbars(d->vbarpolicy == Qt::ScrollBarAlwaysOn ? d->vbar->sizeHint().width() : 0,
+ d->hbarpolicy == Qt::ScrollBarAlwaysOn ? d->hbar->sizeHint().height() : 0);
+ d->sizeHint = frame + scrollbars + viewportSizeHint();
+ }
+ return d->sizeHint;
+}
+
+/*!
+ \since 5.2
+ Returns the recommended size for the viewport.
+ The default implementation returns viewport()->sizeHint().
+ Note that the size is just the viewport's size, without any scroll bars visible.
+ */
+QSize QAbstractScrollArea::viewportSizeHint() const
+{
+ Q_D(const QAbstractScrollArea);
+ if (d->viewport) {
+ const QSize sh = d->viewport->sizeHint();
+ if (sh.isValid()) {
+ return sh;
+ }
+ }
+ const int h = qMax(10, fontMetrics().height());
+ return QSize(6 * h, 4 * h);
+}
+
+/*!
+ \since 5.2
+ \property QAbstractScrollArea::sizeAdjustPolicy
+ This property holds the policy describing how the size of the scroll area changes when the
+ size of the viewport changes.
+
+ The default policy is QAbstractScrollArea::AdjustIgnored.
+ Changing this property might actually resize the scrollarea.
+*/
+
+QAbstractScrollArea::SizeAdjustPolicy QAbstractScrollArea::sizeAdjustPolicy() const
+{
+ Q_D(const QAbstractScrollArea);
+ return d->sizeAdjustPolicy;
+}
+
+void QAbstractScrollArea::setSizeAdjustPolicy(SizeAdjustPolicy policy)
+{
+ Q_D(QAbstractScrollArea);
+ if (d->sizeAdjustPolicy == policy)
+ return;
+
+ d->sizeAdjustPolicy = policy;
+ d->sizeHint = QSize();
+ updateGeometry();
}
/*!
@@ -1559,16 +1633,6 @@ void QAbstractScrollArea::setupViewport(QWidget *viewport)
Q_UNUSED(viewport);
}
-/*!
- \internal
-
- This method is reserved for future use.
-*/
-QSize QAbstractScrollArea::viewportSizeHint() const
-{
- return QSize();
-}
-
QT_END_NAMESPACE
#include "moc_qabstractscrollarea.cpp"
diff --git a/src/widgets/widgets/qabstractscrollarea.h b/src/widgets/widgets/qabstractscrollarea.h
index ccf16b5e5c..fb9562db1b 100644
--- a/src/widgets/widgets/qabstractscrollarea.h
+++ b/src/widgets/widgets/qabstractscrollarea.h
@@ -56,13 +56,22 @@ class QAbstractScrollAreaPrivate;
class Q_WIDGETS_EXPORT QAbstractScrollArea : public QFrame
{
Q_OBJECT
+
+ Q_ENUMS(SizeAdjustPolicy)
Q_PROPERTY(Qt::ScrollBarPolicy verticalScrollBarPolicy READ verticalScrollBarPolicy WRITE setVerticalScrollBarPolicy)
Q_PROPERTY(Qt::ScrollBarPolicy horizontalScrollBarPolicy READ horizontalScrollBarPolicy WRITE setHorizontalScrollBarPolicy)
+ Q_PROPERTY(SizeAdjustPolicy sizeAdjustPolicy READ sizeAdjustPolicy WRITE setSizeAdjustPolicy)
public:
explicit QAbstractScrollArea(QWidget* parent=0);
~QAbstractScrollArea();
+ enum SizeAdjustPolicy {
+ AdjustIgnored,
+ AdjustToContentsOnFirstShow,
+ AdjustToContents
+ };
+
Qt::ScrollBarPolicy verticalScrollBarPolicy() const;
void setVerticalScrollBarPolicy(Qt::ScrollBarPolicy);
QScrollBar *verticalScrollBar() const;
@@ -89,6 +98,9 @@ public:
virtual void setupViewport(QWidget *viewport);
+ SizeAdjustPolicy sizeAdjustPolicy() const;
+ void setSizeAdjustPolicy(SizeAdjustPolicy policy);
+
protected:
QAbstractScrollArea(QAbstractScrollAreaPrivate &dd, QWidget *parent = 0);
void setViewportMargins(int left, int top, int right, int bottom);
diff --git a/src/widgets/widgets/qabstractscrollarea_p.h b/src/widgets/widgets/qabstractscrollarea_p.h
index 34d767fe29..3093c2f812 100644
--- a/src/widgets/widgets/qabstractscrollarea_p.h
+++ b/src/widgets/widgets/qabstractscrollarea_p.h
@@ -75,6 +75,10 @@ public:
QScrollBar *hbar, *vbar;
Qt::ScrollBarPolicy vbarpolicy, hbarpolicy;
+ bool shownOnce;
+ mutable QSize sizeHint;
+ QAbstractScrollArea::SizeAdjustPolicy sizeAdjustPolicy;
+
QWidget *viewport;
QWidget *cornerWidget;
QRect cornerPaintingRect;
diff --git a/src/widgets/widgets/qcombobox.cpp b/src/widgets/widgets/qcombobox.cpp
index afe8f1c3f4..90310308c3 100644
--- a/src/widgets/widgets/qcombobox.cpp
+++ b/src/widgets/widgets/qcombobox.cpp
@@ -407,7 +407,7 @@ void QComboBoxPrivateContainer::leaveEvent(QEvent *)
}
QComboBoxPrivateContainer::QComboBoxPrivateContainer(QAbstractItemView *itemView, QComboBox *parent)
- : QFrame(parent, Qt::Popup), combo(parent), view(0), top(0), bottom(0)
+ : QFrame(parent, Qt::Popup), combo(parent), view(0), top(0), bottom(0), maybeIgnoreMouseButtonRelease(false)
{
// we need the combobox and itemview
Q_ASSERT(parent);
@@ -667,10 +667,15 @@ bool QComboBoxPrivateContainer::eventFilter(QObject *o, QEvent *e)
}
}
break;
+ case QEvent::MouseButtonPress:
+ maybeIgnoreMouseButtonRelease = false;
+ break;
case QEvent::MouseButtonRelease: {
+ bool ignoreEvent = maybeIgnoreMouseButtonRelease && popupTimer.elapsed() < QApplication::doubleClickInterval();
+
QMouseEvent *m = static_cast<QMouseEvent *>(e);
if (isVisible() && view->rect().contains(m->pos()) && view->currentIndex().isValid()
- && !blockMouseReleaseTimer.isActive()
+ && !blockMouseReleaseTimer.isActive() && !ignoreEvent
&& (view->currentIndex().flags() & Qt::ItemIsEnabled)
&& (view->currentIndex().flags() & Qt::ItemIsSelectable)) {
combo->hidePopup();
@@ -2086,6 +2091,20 @@ QString QComboBox::currentText() const
}
/*!
+ \property QComboBox::currentData
+ \brief the data for the current item
+ \since 5.2
+
+ By default, for an empty combo box or a combo box in which no current
+ item is set, this property contains an invalid QVariant.
+*/
+QVariant QComboBox::currentData(int role) const
+{
+ Q_D(const QComboBox);
+ return d->currentIndex.data(role);
+}
+
+/*!
Returns the text for the given \a index in the combobox.
*/
QString QComboBox::itemText(int index) const
@@ -2548,6 +2567,7 @@ void QComboBox::showPopup()
container->setUpdatesEnabled(false);
#endif
+ bool startTimer = !container->isVisible();
container->raise();
container->show();
container->updateScrollers();
@@ -2567,6 +2587,10 @@ void QComboBox::showPopup()
if (QApplication::keypadNavigationEnabled())
view()->setEditFocus(true);
#endif
+ if (startTimer) {
+ container->popupTimer.start();
+ container->maybeIgnoreMouseButtonRelease = true;
+ }
}
/*!
@@ -2862,6 +2886,11 @@ void QComboBox::mousePressEvent(QMouseEvent *e)
}
#endif
showPopup();
+ // The code below ensures that regular mousepress and pick item still works
+ // If it was not called the viewContainer would ignore event since it didn't have
+ // a mousePressEvent first.
+ if (d->viewContainer())
+ d->viewContainer()->maybeIgnoreMouseButtonRelease = false;
} else {
#ifdef QT_KEYPAD_NAVIGATION
if (QApplication::keypadNavigationEnabled() && sc == QStyle::SC_ComboBoxEditField && d->lineEdit) {
diff --git a/src/widgets/widgets/qcombobox.h b/src/widgets/widgets/qcombobox.h
index 2fafe79f7a..0002cd08cb 100644
--- a/src/widgets/widgets/qcombobox.h
+++ b/src/widgets/widgets/qcombobox.h
@@ -66,6 +66,7 @@ class Q_WIDGETS_EXPORT QComboBox : public QWidget
Q_PROPERTY(int count READ count)
Q_PROPERTY(QString currentText READ currentText WRITE setCurrentText NOTIFY currentTextChanged USER true)
Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged)
+ Q_PROPERTY(QVariant currentData READ currentData)
Q_PROPERTY(int maxVisibleItems READ maxVisibleItems WRITE setMaxVisibleItems)
Q_PROPERTY(int maxCount READ maxCount WRITE setMaxCount)
Q_PROPERTY(InsertPolicy insertPolicy READ insertPolicy WRITE setInsertPolicy)
@@ -167,8 +168,8 @@ public:
void setModelColumn(int visibleColumn);
int currentIndex() const;
-
QString currentText() const;
+ QVariant currentData(int role = Qt::UserRole) const;
QString itemText(int index) const;
QIcon itemIcon(int index) const;
diff --git a/src/widgets/widgets/qcombobox_p.h b/src/widgets/widgets/qcombobox_p.h
index 07ba9b0925..1ad2aa455a 100644
--- a/src/widgets/widgets/qcombobox_p.h
+++ b/src/widgets/widgets/qcombobox_p.h
@@ -254,6 +254,10 @@ private:
QAbstractItemView *view;
QComboBoxPrivateScroller *top;
QComboBoxPrivateScroller *bottom;
+ bool maybeIgnoreMouseButtonRelease;
+ QElapsedTimer popupTimer;
+
+ friend class QComboBox;
};
class QComboMenuDelegate : public QAbstractItemDelegate
diff --git a/src/widgets/widgets/qdialogbuttonbox.cpp b/src/widgets/widgets/qdialogbuttonbox.cpp
index bc5d84e259..226969cdd1 100644
--- a/src/widgets/widgets/qdialogbuttonbox.cpp
+++ b/src/widgets/widgets/qdialogbuttonbox.cpp
@@ -669,6 +669,21 @@ QDialogButtonBox::QDialogButtonBox(Qt::Orientation orientation, QWidget *parent)
}
/*!
+ \since 5.2
+
+ Constructs a horizontal button box with the given \a parent, containing
+ the standard buttons specified by \a buttons.
+
+ \sa orientation, addButton()
+*/
+QDialogButtonBox::QDialogButtonBox(StandardButtons buttons, QWidget *parent)
+ : QWidget(*new QDialogButtonBoxPrivate(Qt::Horizontal), parent, 0)
+{
+ d_func()->initLayout();
+ d_func()->createStandardButtons(buttons);
+}
+
+/*!
Constructs a button box with the given \a orientation and \a parent, containing
the standard buttons specified by \a buttons.
diff --git a/src/widgets/widgets/qdialogbuttonbox.h b/src/widgets/widgets/qdialogbuttonbox.h
index 6715c590e2..d8e1a997d4 100644
--- a/src/widgets/widgets/qdialogbuttonbox.h
+++ b/src/widgets/widgets/qdialogbuttonbox.h
@@ -115,7 +115,8 @@ public:
QDialogButtonBox(QWidget *parent = 0);
QDialogButtonBox(Qt::Orientation orientation, QWidget *parent = 0);
- QDialogButtonBox(StandardButtons buttons, Qt::Orientation orientation = Qt::Horizontal,
+ explicit QDialogButtonBox(StandardButtons buttons, QWidget *parent = 0);
+ QDialogButtonBox(StandardButtons buttons, Qt::Orientation orientation,
QWidget *parent = 0);
~QDialogButtonBox();
diff --git a/src/widgets/widgets/qfontcombobox.cpp b/src/widgets/widgets/qfontcombobox.cpp
index 5f929caf03..0b0efa2bdf 100644
--- a/src/widgets/widgets/qfontcombobox.cpp
+++ b/src/widgets/widgets/qfontcombobox.cpp
@@ -54,6 +54,88 @@
QT_BEGIN_NAMESPACE
+static QFontDatabase::WritingSystem writingSystemFromScript(QLocale::Script script)
+{
+ switch (script) {
+ case QLocale::ArabicScript:
+ return QFontDatabase::Arabic;
+ case QLocale::CyrillicScript:
+ return QFontDatabase::Cyrillic;
+ case QLocale::GurmukhiScript:
+ return QFontDatabase::Gurmukhi;
+ case QLocale::SimplifiedHanScript:
+ return QFontDatabase::SimplifiedChinese;
+ case QLocale::TraditionalHanScript:
+ return QFontDatabase::TraditionalChinese;
+ case QLocale::LatinScript:
+ return QFontDatabase::Latin;
+ case QLocale::ArmenianScript:
+ return QFontDatabase::Armenian;
+ case QLocale::BengaliScript:
+ return QFontDatabase::Bengali;
+ case QLocale::DevanagariScript:
+ return QFontDatabase::Devanagari;
+ case QLocale::GeorgianScript:
+ return QFontDatabase::Georgian;
+ case QLocale::GreekScript:
+ return QFontDatabase::Greek;
+ case QLocale::GujaratiScript:
+ return QFontDatabase::Gujarati;
+ case QLocale::HebrewScript:
+ return QFontDatabase::Hebrew;
+ case QLocale::JapaneseScript:
+ return QFontDatabase::Japanese;
+ case QLocale::KhmerScript:
+ return QFontDatabase::Khmer;
+ case QLocale::KannadaScript:
+ return QFontDatabase::Kannada;
+ case QLocale::KoreanScript:
+ return QFontDatabase::Korean;
+ case QLocale::LaoScript:
+ return QFontDatabase::Lao;
+ case QLocale::MalayalamScript:
+ return QFontDatabase::Malayalam;
+ case QLocale::MyanmarScript:
+ return QFontDatabase::Myanmar;
+ case QLocale::TamilScript:
+ return QFontDatabase::Tamil;
+ case QLocale::TeluguScript:
+ return QFontDatabase::Telugu;
+ case QLocale::ThaanaScript:
+ return QFontDatabase::Thaana;
+ case QLocale::ThaiScript:
+ return QFontDatabase::Thai;
+ case QLocale::TibetanScript:
+ return QFontDatabase::Tibetan;
+ case QLocale::SinhalaScript:
+ return QFontDatabase::Sinhala;
+ case QLocale::SyriacScript:
+ return QFontDatabase::Syriac;
+ case QLocale::OriyaScript:
+ return QFontDatabase::Oriya;
+ case QLocale::OghamScript:
+ return QFontDatabase::Ogham;
+ case QLocale::RunicScript:
+ return QFontDatabase::Runic;
+ case QLocale::NkoScript:
+ return QFontDatabase::Nko;
+ default:
+ return QFontDatabase::Any;
+ }
+}
+
+static QFontDatabase::WritingSystem writingSystemFromLocale()
+{
+ QStringList uiLanguages = QLocale::system().uiLanguages();
+ QLocale::Script script;
+ if (!uiLanguages.isEmpty())
+ script = QLocale(uiLanguages.at(0)).script();
+ else
+ script = QLocale::system().script();
+
+ return writingSystemFromScript(script);
+}
+
static QFontDatabase::WritingSystem writingSystemForFont(const QFont &font, bool *hasLatin)
{
QList<QFontDatabase::WritingSystem> writingSystems = QFontDatabase().writingSystems(font.family());
@@ -66,7 +148,22 @@ static QFontDatabase::WritingSystem writingSystemForFont(const QFont &font, bool
if (writingSystems.isEmpty())
return QFontDatabase::Any;
- QFontDatabase::WritingSystem system = writingSystems.last();
+ QFontDatabase::WritingSystem system = writingSystemFromLocale();
+
+ if (writingSystems.contains(system))
+ return system;
+
+ if (system == QFontDatabase::TraditionalChinese
+ && writingSystems.contains(QFontDatabase::SimplifiedChinese)) {
+ return QFontDatabase::SimplifiedChinese;
+ }
+
+ if (system == QFontDatabase::SimplifiedChinese
+ && writingSystems.contains(QFontDatabase::TraditionalChinese)) {
+ return QFontDatabase::TraditionalChinese;
+ }
+
+ system = writingSystems.last();
if (!*hasLatin) {
// we need to show something
diff --git a/src/widgets/widgets/qlineedit.cpp b/src/widgets/widgets/qlineedit.cpp
index 70083d7267..a8b6b1a10c 100644
--- a/src/widgets/widgets/qlineedit.cpp
+++ b/src/widgets/widgets/qlineedit.cpp
@@ -351,7 +351,7 @@ void QLineEdit::setPlaceholderText(const QString& placeholderText)
Q_D(QLineEdit);
if (d->placeholderText != placeholderText) {
d->placeholderText = placeholderText;
- if (!hasFocus())
+ if (d->control->text().isEmpty())
update();
}
}
@@ -420,6 +420,96 @@ bool QLineEdit::hasFrame() const
return d->frame;
}
+/*!
+ \enum QLineEdit::ActionPosition
+
+ This enum type describes how a line edit should display the action widgets to be
+ added.
+
+ \value LeadingPosition The widget is displayed to the left of the text
+ when using layout direction \c Qt::LeftToRight or to
+ the right when using \c Qt::RightToLeft, respectively.
+
+ \value TrailingPosition The widget is displayed to the right of the text
+ when using layout direction \c Qt::LeftToRight or to
+ the left when using \c Qt::RightToLeft, respectively.
+
+ \sa addAction(), removeAction(), QWidget::layoutDirection
+
+ \since 5.2
+*/
+
+/*!
+ \fn void QLineEdit::addAction(QAction *action)
+ \overload
+ \internal
+*/
+
+/*!
+ \overload
+
+ Adds the \a action to the list of actions at the \a position.
+
+ \since 5.2
+*/
+
+void QLineEdit::addAction(QAction *action, ActionPosition position)
+{
+ Q_D(QLineEdit);
+ QWidget::addAction(action);
+ d->addAction(action, 0, position);
+}
+
+/*!
+ \overload
+
+ Creates a new action with the given \a icon at the \a position.
+
+ \since 5.2
+*/
+
+QAction *QLineEdit::addAction(const QIcon &icon, ActionPosition position)
+{
+ QAction *result = new QAction(icon, QString(), this);
+ addAction(result, position);
+ return result;
+}
+
+/*!
+ \property QLineEdit::clearButtonEnabled
+ \brief Whether the line edit displays a clear button when it is not empty.
+
+ If enabled, the line edit displays a trailing \e clear button when it contains
+ some text, otherwise the line edit does not show a clear button (the
+ default).
+
+ \sa addAction(), removeAction()
+ \since 5.2
+*/
+
+static const char clearButtonActionNameC[] = "_q_qlineeditclearaction";
+
+void QLineEdit::setClearButtonEnabled(bool enable)
+{
+ Q_D(QLineEdit);
+ if (enable == isClearButtonEnabled())
+ return;
+ if (enable) {
+ QAction *clearAction = new QAction(d->clearButtonIcon(), QString(), this);
+ clearAction->setObjectName(QLatin1String(clearButtonActionNameC));
+ d->addAction(clearAction, 0, QLineEdit::TrailingPosition, QLineEditPrivate::SideWidgetClearButton | QLineEditPrivate::SideWidgetFadeInWithText);
+ } else {
+ QAction *clearAction = findChild<QAction *>(QLatin1String(clearButtonActionNameC));
+ Q_ASSERT(clearAction);
+ removeAction(clearAction);
+ delete clearAction;
+ }
+}
+
+bool QLineEdit::isClearButtonEnabled() const
+{
+ return findChild<QAction *>(QLatin1String(clearButtonActionNameC));
+}
void QLineEdit::setFrame(bool enable)
{
@@ -606,7 +696,7 @@ QSize QLineEdit::sizeHint() const
+ d->topTextMargin + d->bottomTextMargin
+ d->topmargin + d->bottommargin;
int w = fm.width(QLatin1Char('x')) * 17 + 2*d->horizontalMargin
- + d->leftTextMargin + d->rightTextMargin
+ + d->effectiveLeftTextMargin() + d->effectiveRightTextMargin()
+ d->leftmargin + d->rightmargin; // "some"
QStyleOptionFrameV2 opt;
initStyleOption(&opt);
@@ -967,7 +1057,6 @@ void QLineEdit::setDragEnabled(bool b)
d->dragEnabled = b;
}
-
/*!
\property QLineEdit::cursorMoveStyle
\brief the movement style of cursor in this line edit
@@ -1350,8 +1439,11 @@ bool QLineEdit::event(QEvent * e)
|| style()->styleHint(QStyle::SH_BlinkCursorWhenTextSelected, &opt, this))
d->setCursorVisible(true);
}
+ } else if (e->type() == QEvent::ActionRemoved) {
+ d->removeAction(static_cast<QActionEvent *>(e));
+ } else if (e->type() == QEvent::Resize) {
+ d->positionSideWidgets();
}
-
#ifdef QT_KEYPAD_NAVIGATION
if (QApplication::keypadNavigationEnabled()) {
if (e->type() == QEvent::EnterEditFocus) {
@@ -1777,9 +1869,9 @@ void QLineEdit::paintEvent(QPaintEvent *)
initStyleOption(&panel);
style()->drawPrimitive(QStyle::PE_PanelLineEdit, &panel, &p, this);
r = style()->subElementRect(QStyle::SE_LineEditContents, &panel, this);
- r.setX(r.x() + d->leftTextMargin);
+ r.setX(r.x() + d->effectiveLeftTextMargin());
r.setY(r.y() + d->topTextMargin);
- r.setRight(r.right() - d->rightTextMargin);
+ r.setRight(r.right() - d->effectiveRightTextMargin());
r.setBottom(r.bottom() - d->bottomTextMargin);
p.setClipRect(r);
@@ -1983,6 +2075,13 @@ void QLineEdit::contextMenuEvent(QContextMenuEvent *event)
}
}
+static inline void setActionIcon(QAction *action, const QString &name)
+{
+ const QIcon icon = QIcon::fromTheme(name);
+ if (!icon.isNull())
+ action->setIcon(icon);
+}
+
/*! This function creates the standard context menu which is shown
when the user clicks on the line edit with the right mouse
button. It is called from the default contextMenuEvent() handler.
@@ -1999,10 +2098,12 @@ QMenu *QLineEdit::createStandardContextMenu()
if (!isReadOnly()) {
action = popup->addAction(QLineEdit::tr("&Undo") + ACCEL_KEY(QKeySequence::Undo));
action->setEnabled(d->control->isUndoAvailable());
+ setActionIcon(action, QStringLiteral("edit-undo"));
connect(action, SIGNAL(triggered()), SLOT(undo()));
action = popup->addAction(QLineEdit::tr("&Redo") + ACCEL_KEY(QKeySequence::Redo));
action->setEnabled(d->control->isRedoAvailable());
+ setActionIcon(action, QStringLiteral("edit-redo"));
connect(action, SIGNAL(triggered()), SLOT(redo()));
popup->addSeparator();
@@ -2013,17 +2114,20 @@ QMenu *QLineEdit::createStandardContextMenu()
action = popup->addAction(QLineEdit::tr("Cu&t") + ACCEL_KEY(QKeySequence::Cut));
action->setEnabled(!d->control->isReadOnly() && d->control->hasSelectedText()
&& d->control->echoMode() == QLineEdit::Normal);
+ setActionIcon(action, QStringLiteral("edit-cut"));
connect(action, SIGNAL(triggered()), SLOT(cut()));
}
action = popup->addAction(QLineEdit::tr("&Copy") + ACCEL_KEY(QKeySequence::Copy));
action->setEnabled(d->control->hasSelectedText()
&& d->control->echoMode() == QLineEdit::Normal);
+ setActionIcon(action, QStringLiteral("edit-copy"));
connect(action, SIGNAL(triggered()), SLOT(copy()));
if (!isReadOnly()) {
action = popup->addAction(QLineEdit::tr("&Paste") + ACCEL_KEY(QKeySequence::Paste));
action->setEnabled(!d->control->isReadOnly() && !QApplication::clipboard()->text().isEmpty());
+ setActionIcon(action, QStringLiteral("edit-paste"));
connect(action, SIGNAL(triggered()), SLOT(paste()));
}
#endif
@@ -2031,6 +2135,7 @@ QMenu *QLineEdit::createStandardContextMenu()
if (!isReadOnly()) {
action = popup->addAction(QLineEdit::tr("Delete"));
action->setEnabled(!d->control->isReadOnly() && !d->control->text().isEmpty() && d->control->hasSelectedText());
+ setActionIcon(action, QStringLiteral("edit-delete"));
connect(action, SIGNAL(triggered()), d->control, SLOT(_q_deleteSelected()));
}
@@ -2070,8 +2175,15 @@ void QLineEdit::changeEvent(QEvent *ev)
initStyleOption(&opt);
d->control->setPasswordCharacter(style()->styleHint(QStyle::SH_LineEdit_PasswordCharacter, &opt, this));
}
+ d->m_iconSize = QSize();
update();
break;
+ case QEvent::LayoutDirectionChange:
+ foreach (const QLineEditPrivate::SideWidgetEntry &e, d->trailingSideWidgets) // Refresh icon to show arrow in right direction.
+ if (e.flags & QLineEditPrivate::SideWidgetClearButton)
+ static_cast<QLineEditIconButton *>(e.widget)->setIcon(d->clearButtonIcon());
+ d->positionSideWidgets();
+ break;
default:
break;
}
diff --git a/src/widgets/widgets/qlineedit.h b/src/widgets/widgets/qlineedit.h
index e2b944314b..3d52863db2 100644
--- a/src/widgets/widgets/qlineedit.h
+++ b/src/widgets/widgets/qlineedit.h
@@ -59,12 +59,14 @@ class QCompleter;
class QStyleOptionFrame;
class QAbstractSpinBox;
class QDateTimeEdit;
+class QIcon;
+class QToolButton;
class Q_WIDGETS_EXPORT QLineEdit : public QWidget
{
Q_OBJECT
- Q_ENUMS(EchoMode)
+ Q_ENUMS(ActionPosition EchoMode)
Q_PROPERTY(QString inputMask READ inputMask WRITE setInputMask)
Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged USER true)
Q_PROPERTY(int maxLength READ maxLength WRITE setMaxLength)
@@ -83,8 +85,13 @@ class Q_WIDGETS_EXPORT QLineEdit : public QWidget
Q_PROPERTY(bool acceptableInput READ hasAcceptableInput)
Q_PROPERTY(QString placeholderText READ placeholderText WRITE setPlaceholderText)
Q_PROPERTY(Qt::CursorMoveStyle cursorMoveStyle READ cursorMoveStyle WRITE setCursorMoveStyle)
-
+ Q_PROPERTY(bool clearButtonEnabled READ isClearButtonEnabled WRITE setClearButtonEnabled)
public:
+ enum ActionPosition {
+ LeadingPosition,
+ TrailingPosition
+ };
+
explicit QLineEdit(QWidget* parent=0);
explicit QLineEdit(const QString &, QWidget* parent=0);
~QLineEdit();
@@ -102,6 +109,9 @@ public:
void setFrame(bool);
bool hasFrame() const;
+ void setClearButtonEnabled(bool enable);
+ bool isClearButtonEnabled() const;
+
enum EchoMode { Normal, NoEcho, Password, PasswordEchoOnEdit };
EchoMode echoMode() const;
void setEchoMode(EchoMode);
@@ -164,6 +174,16 @@ public:
void getTextMargins(int *left, int *top, int *right, int *bottom) const;
QMargins textMargins() const;
+#ifdef Q_NO_USING_KEYWORD
+ inline void addAction(QAction *action)
+ { QWidget::addAction(action); }
+#else
+ using QWidget::addAction;
+#endif
+
+ void addAction(QAction *action, ActionPosition position);
+ QAction *addAction(const QIcon &icon, ActionPosition position);
+
public Q_SLOTS:
void setText(const QString &);
void clear();
@@ -240,6 +260,7 @@ private:
#endif
Q_PRIVATE_SLOT(d_func(), void _q_selectionChanged())
Q_PRIVATE_SLOT(d_func(), void _q_updateNeeded(const QRect &))
+ Q_PRIVATE_SLOT(d_func(), void _q_textChanged(const QString &))
};
#endif // QT_NO_LINEEDIT
diff --git a/src/widgets/widgets/qlineedit_p.cpp b/src/widgets/widgets/qlineedit_p.cpp
index 1999216e65..99d6d0b8d9 100644
--- a/src/widgets/widgets/qlineedit_p.cpp
+++ b/src/widgets/widgets/qlineedit_p.cpp
@@ -44,8 +44,10 @@
#ifndef QT_NO_LINEEDIT
+#include "qvariant.h"
#include "qabstractitemview.h"
#include "qdrag.h"
+#include "qwidgetaction.h"
#include "qclipboard.h"
#ifndef QT_NO_ACCESSIBILITY
#include "qaccessible.h"
@@ -53,6 +55,7 @@
#ifndef QT_NO_IM
#include "qinputmethod.h"
#include "qlist.h"
+#include <qpropertyanimation.h>
#endif
QT_BEGIN_NAMESPACE
@@ -219,9 +222,9 @@ QRect QLineEditPrivate::adjustedContentsRect() const
QStyleOptionFrameV2 opt;
q->initStyleOption(&opt);
QRect r = q->style()->subElementRect(QStyle::SE_LineEditContents, &opt, q);
- r.setX(r.x() + leftTextMargin);
+ r.setX(r.x() + effectiveLeftTextMargin());
r.setY(r.y() + topTextMargin);
- r.setRight(r.right() - rightTextMargin);
+ r.setRight(r.right() - effectiveRightTextMargin());
r.setBottom(r.bottom() - bottomTextMargin);
return r;
}
@@ -297,6 +300,170 @@ void QLineEditPrivate::drag()
#endif // QT_NO_DRAGANDDROP
+QLineEditIconButton::QLineEditIconButton(QWidget *parent)
+ : QToolButton(parent)
+ , m_opacity(0)
+{
+#ifndef QT_NO_CURSOR
+ setCursor(Qt::ArrowCursor);
+#endif
+ setFocusPolicy(Qt::NoFocus);
+}
+
+void QLineEditIconButton::paintEvent(QPaintEvent *)
+{
+ QPainter painter(this);
+ // Note isDown should really use the active state but in most styles
+ // this has no proper feedback
+ QIcon::Mode state = QIcon::Disabled;
+ if (isEnabled())
+ state = isDown() ? QIcon::Selected : QIcon::Normal;
+ const QPixmap iconPixmap = icon().pixmap(QSize(IconButtonSize, IconButtonSize),
+ state, QIcon::Off);
+ QRect pixmapRect = QRect(0, 0, iconPixmap.width(), iconPixmap.height());
+ pixmapRect.moveCenter(rect().center());
+ painter.setOpacity(m_opacity);
+ painter.drawPixmap(pixmapRect, iconPixmap);
+}
+
+void QLineEditIconButton::setOpacity(qreal value)
+{
+ if (!qFuzzyCompare(m_opacity, value)) {
+ m_opacity = value;
+ update();
+ }
+}
+
+void QLineEditIconButton::startOpacityAnimation(qreal endValue)
+{
+ QPropertyAnimation *animation = new QPropertyAnimation(this, QByteArrayLiteral("opacity"));
+ animation->setDuration(160);
+ animation->setEndValue(endValue);
+ animation->start(QAbstractAnimation::DeleteWhenStopped);
+}
+
+void QLineEditPrivate::_q_textChanged(const QString &text)
+{
+ if (hasSideWidgets()) {
+ const int newTextSize = text.size();
+ if (!newTextSize || !lastTextSize) {
+ lastTextSize = newTextSize;
+ const bool fadeIn = newTextSize > 0;
+ foreach (const SideWidgetEntry &e, leadingSideWidgets) {
+ if (e.flags & SideWidgetFadeInWithText)
+ static_cast<QLineEditIconButton *>(e.widget)->animateShow(fadeIn);
+ }
+ foreach (const SideWidgetEntry &e, trailingSideWidgets) {
+ if (e.flags & SideWidgetFadeInWithText)
+ static_cast<QLineEditIconButton *>(e.widget)->animateShow(fadeIn);
+ }
+ }
+ }
+}
+
+QSize QLineEditPrivate::iconSize() const
+{
+ if (!m_iconSize.isValid()) // This might require style-specific handling (pixel metric).
+ m_iconSize = QSize(QLineEditIconButton::IconButtonSize + 6, QLineEditIconButton::IconButtonSize + 2);
+ return m_iconSize;
+}
+
+QIcon QLineEditPrivate::clearButtonIcon() const
+{
+ Q_Q(const QLineEdit);
+ QStyleOptionFrameV2 styleOption;
+ q->initStyleOption(&styleOption);
+ return QIcon(q->style()->standardPixmap(QStyle::SP_LineEditClearButton, &styleOption, q));
+}
+
+void QLineEditPrivate::positionSideWidgets()
+{
+ Q_Q(QLineEdit);
+ if (hasSideWidgets()) {
+ const QRect contentRect = q->rect();
+ const QSize iconSize = QLineEditPrivate::iconSize();
+ const int delta = QLineEditIconButton::IconMargin + iconSize.width();
+ QRect widgetGeometry(QPoint(QLineEditIconButton::IconMargin, (contentRect.height() - iconSize.height()) / 2), iconSize);
+ foreach (const SideWidgetEntry &e, leftSideWidgetList()) {
+ e.widget->setGeometry(widgetGeometry);
+ widgetGeometry.moveLeft(widgetGeometry.left() + delta);
+ }
+ widgetGeometry.moveLeft(contentRect.width() - iconSize.width() - QLineEditIconButton::IconMargin);
+ foreach (const SideWidgetEntry &e, rightSideWidgetList()) {
+ e.widget->setGeometry(widgetGeometry);
+ widgetGeometry.moveLeft(widgetGeometry.left() - delta);
+ }
+ }
+}
+
+QLineEditPrivate::PositionIndexPair QLineEditPrivate::findSideWidget(const QAction *a) const
+{
+ for (int i = 0; i < leadingSideWidgets.size(); ++i) {
+ if (a == leadingSideWidgets.at(i).action)
+ return PositionIndexPair(QLineEdit::LeadingPosition, i);
+ }
+ for (int i = 0; i < trailingSideWidgets.size(); ++i) {
+ if (a == trailingSideWidgets.at(i).action)
+ return PositionIndexPair(QLineEdit::TrailingPosition, i);
+ }
+ return PositionIndexPair(QLineEdit::LeadingPosition, -1);
+}
+
+QWidget *QLineEditPrivate::addAction(QAction *newAction, QAction *before, QLineEdit::ActionPosition position, int flags)
+{
+ Q_Q(QLineEdit);
+ if (!newAction)
+ return 0;
+ QWidget *w = 0;
+ // Store flags about QWidgetAction here since removeAction() may be called from ~QAction,
+ // in which a qobject_cast<> no longer works.
+ if (QWidgetAction *widgetAction = qobject_cast<QWidgetAction *>(newAction)) {
+ if ((w = widgetAction->requestWidget(q)))
+ flags |= SideWidgetCreatedByWidgetAction;
+ }
+ if (!w) {
+ QLineEditIconButton *toolButton = new QLineEditIconButton(q);
+ toolButton->setIcon(newAction->icon());
+ toolButton->setOpacity(lastTextSize > 0 || !(flags & SideWidgetFadeInWithText) ? 1 : 0);
+ if (flags & SideWidgetClearButton)
+ QObject::connect(toolButton, SIGNAL(clicked()), q, SLOT(clear()));
+ toolButton->setDefaultAction(newAction);
+ w = toolButton;
+ }
+ if (!hasSideWidgets()) { // initial setup.
+ QObject::connect(q, SIGNAL(textChanged(QString)), q, SLOT(_q_textChanged(QString)));
+ lastTextSize = q->text().size();
+ }
+ // If there is a 'before' action, it takes preference
+ PositionIndexPair positionIndex = before ? findSideWidget(before) : PositionIndexPair(position, -1);
+ SideWidgetEntryList &list = positionIndex.first == QLineEdit::TrailingPosition ? trailingSideWidgets : leadingSideWidgets;
+ if (positionIndex.second < 0)
+ positionIndex.second = list.size();
+ list.insert(positionIndex.second, SideWidgetEntry(w, newAction, flags));
+ positionSideWidgets();
+ w->show();
+ return w;
+}
+
+void QLineEditPrivate::removeAction(const QActionEvent *e)
+{
+ Q_Q(QLineEdit);
+ QAction *action = e->action();
+ const PositionIndexPair positionIndex = findSideWidget(action);
+ if (positionIndex.second == -1)
+ return;
+ SideWidgetEntryList &list = positionIndex.first == QLineEdit::TrailingPosition ? trailingSideWidgets : leadingSideWidgets;
+ SideWidgetEntry entry = list.takeAt(positionIndex.second);
+ if (entry.flags & SideWidgetCreatedByWidgetAction)
+ static_cast<QWidgetAction *>(entry.action)->releaseWidget(entry.widget);
+ else
+ delete entry.widget;
+ positionSideWidgets();
+ if (!hasSideWidgets()) // Last widget, remove connection
+ QObject::disconnect(q, SIGNAL(textChanged(QString)), q, SLOT(_q_textChanged(QString)));
+ q->update();
+}
+
QT_END_NAMESPACE
#endif
diff --git a/src/widgets/widgets/qlineedit_p.h b/src/widgets/widgets/qlineedit_p.h
index 4eb35b7dc6..8fe45972ff 100644
--- a/src/widgets/widgets/qlineedit_p.h
+++ b/src/widgets/widgets/qlineedit_p.h
@@ -58,7 +58,9 @@
#ifndef QT_NO_LINEEDIT
#include "private/qwidget_p.h"
#include "QtWidgets/qlineedit.h"
+#include "QtWidgets/qtoolbutton.h"
#include "QtGui/qtextlayout.h"
+#include "QtGui/qicon.h"
#include "QtWidgets/qstyleoption.h"
#include "QtCore/qbasictimer.h"
#include "QtWidgets/qcompleter.h"
@@ -69,16 +71,55 @@
QT_BEGIN_NAMESPACE
+// QLineEditIconButton: This is a simple helper class that represents clickable icons that fade in with text
+
+class QLineEditIconButton : public QToolButton
+{
+ Q_OBJECT
+ Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity)
+public:
+ enum { IconMargin = 4, IconButtonSize = 16 };
+
+ explicit QLineEditIconButton(QWidget *parent = 0);
+
+ qreal opacity() const { return m_opacity; }
+ void setOpacity(qreal value);
+ void animateShow(bool visible) { startOpacityAnimation(visible ? 1.0 : 0.0); }
+
+protected:
+ void paintEvent(QPaintEvent *event);
+
+private:
+ void startOpacityAnimation(qreal endValue);
+
+ qreal m_opacity;
+};
+
class Q_AUTOTEST_EXPORT QLineEditPrivate : public QWidgetPrivate
{
Q_DECLARE_PUBLIC(QLineEdit)
public:
+ enum SideWidgetFlag {
+ SideWidgetFadeInWithText = 0x1,
+ SideWidgetCreatedByWidgetAction = 0x2,
+ SideWidgetClearButton = 0x4
+ };
+
+ struct SideWidgetEntry {
+ SideWidgetEntry(QWidget *w = 0, QAction *a = 0, int _flags = 0) : widget(w), action(a), flags(_flags) {}
+
+ QWidget *widget;
+ QAction *action;
+ int flags;
+ };
+ typedef QList<SideWidgetEntry> SideWidgetEntryList;
QLineEditPrivate()
: control(0), frame(1), contextMenuEnabled(1), cursorVisible(0),
dragEnabled(0), clickCausedFocus(0), hscroll(0), vscroll(0),
alignment(Qt::AlignLeading | Qt::AlignVCenter),
- leftTextMargin(0), topTextMargin(0), rightTextMargin(0), bottomTextMargin(0)
+ leftTextMargin(0), topTextMargin(0), rightTextMargin(0), bottomTextMargin(0),
+ lastTextSize(0)
{
}
@@ -145,15 +186,50 @@ public:
QBasicTimer dndTimer;
void drag();
#endif
+ void _q_textChanged(const QString &);
- int leftTextMargin;
+ int leftTextMargin; // use effectiveLeftTextMargin() in case of icon.
int topTextMargin;
- int rightTextMargin;
+ int rightTextMargin; // use effectiveRightTextMargin() in case of icon.
int bottomTextMargin;
QString placeholderText;
+
+ QWidget *addAction(QAction *newAction, QAction *before, QLineEdit::ActionPosition, int flags = 0);
+ void removeAction(const QActionEvent *e);
+ QSize iconSize() const;
+ QIcon clearButtonIcon() const;
+ void positionSideWidgets();
+ inline bool hasSideWidgets() const { return !leadingSideWidgets.isEmpty() || !trailingSideWidgets.isEmpty(); }
+ inline const SideWidgetEntryList &leftSideWidgetList() const
+ { return q_func()->layoutDirection() == Qt::LeftToRight ? leadingSideWidgets : trailingSideWidgets; }
+ inline const SideWidgetEntryList &rightSideWidgetList() const
+ { return q_func()->layoutDirection() == Qt::LeftToRight ? trailingSideWidgets : leadingSideWidgets; }
+
+ int effectiveLeftTextMargin() const;
+ int effectiveRightTextMargin() const;
+
+private:
+ typedef QPair<QLineEdit::ActionPosition, int> PositionIndexPair;
+
+ PositionIndexPair findSideWidget(const QAction *a) const;
+
+ SideWidgetEntryList leadingSideWidgets;
+ SideWidgetEntryList trailingSideWidgets;
+ int lastTextSize;
+ mutable QSize m_iconSize;
};
+inline int QLineEditPrivate::effectiveLeftTextMargin() const
+{
+ return leftTextMargin + leftSideWidgetList().size() * (QLineEditIconButton::IconMargin + iconSize().width());
+}
+
+inline int QLineEditPrivate::effectiveRightTextMargin() const
+{
+ return rightTextMargin + rightSideWidgetList().size() * (QLineEditIconButton::IconMargin + iconSize().width());
+}
+
#endif // QT_NO_LINEEDIT
QT_END_NAMESPACE
diff --git a/src/widgets/widgets/qpushbutton_p.h b/src/widgets/widgets/qpushbutton_p.h
index 93069d295f..142df04825 100644
--- a/src/widgets/widgets/qpushbutton_p.h
+++ b/src/widgets/widgets/qpushbutton_p.h
@@ -39,6 +39,9 @@
**
****************************************************************************/
+#ifndef QPUSHBUTTON_P_H
+#define QPUSHBUTTON_P_H
+
#include "private/qabstractbutton_p.h"
//
@@ -88,3 +91,5 @@ public:
};
QT_END_NAMESPACE
+
+#endif // QPUSHBUTTON_P_H
diff --git a/src/widgets/widgets/qscrollarea.cpp b/src/widgets/widgets/qscrollarea.cpp
index 93c335c56b..2a6d4620d7 100644
--- a/src/widgets/widgets/qscrollarea.cpp
+++ b/src/widgets/widgets/qscrollarea.cpp
@@ -407,6 +407,18 @@ QSize QScrollArea::sizeHint() const
return sz.boundedTo(QSize(36 * h, 24 * h));
}
+/*!
+ \reimp
+ */
+QSize QScrollArea::viewportSizeHint() const
+{
+ Q_D(const QScrollArea);
+ if (d->widget) {
+ return d->resizable ? d->widget->sizeHint() : d->widget->size();
+ }
+ const int h = fontMetrics().height();
+ return QSize(6 * h, 4 * h);
+}
/*!
diff --git a/src/widgets/widgets/qscrollarea.h b/src/widgets/widgets/qscrollarea.h
index 576c9bc9e0..70af5fbbd7 100644
--- a/src/widgets/widgets/qscrollarea.h
+++ b/src/widgets/widgets/qscrollarea.h
@@ -69,6 +69,8 @@ public:
void setWidgetResizable(bool resizable);
QSize sizeHint() const;
+ QSize viewportSizeHint() const;
+
bool focusNextPrevChild(bool next);
Qt::Alignment alignment() const;
diff --git a/src/widgets/widgets/qscrollbar.cpp b/src/widgets/widgets/qscrollbar.cpp
index e1e2723a2d..05b8935bb5 100644
--- a/src/widgets/widgets/qscrollbar.cpp
+++ b/src/widgets/widgets/qscrollbar.cpp
@@ -510,6 +510,11 @@ void QScrollBar::wheelEvent(QWheelEvent *event)
Q_D(QScrollBar);
if (d->scrollByDelta(event->orientation(), event->modifiers(), delta))
event->accept();
+
+ if (event->phase() == Qt::ScrollBegin)
+ d->setTransient(false);
+ else if (event->phase() == Qt::ScrollEnd)
+ d->setTransient(true);
}
#endif
diff --git a/src/widgets/widgets/qspinbox.cpp b/src/widgets/widgets/qspinbox.cpp
index 0ce5473ad8..bf4e130d4e 100644
--- a/src/widgets/widgets/qspinbox.cpp
+++ b/src/widgets/widgets/qspinbox.cpp
@@ -78,6 +78,8 @@ public:
q->setInputMethodHints(Qt::ImhDigitsOnly);
setLayoutItemMargins(QStyle::SE_SpinBoxLayoutItem);
}
+
+ int displayIntegerBase;
};
class QDoubleSpinBoxPrivate : public QAbstractSpinBoxPrivate
@@ -425,6 +427,38 @@ void QSpinBox::setRange(int minimum, int maximum)
}
/*!
+ \property QSpinBox::displayIntegerBase
+
+ \brief the base used to display the value of the spin box
+
+ The default displayIntegerBase value is 10.
+
+ \sa textFromValue(), valueFromText()
+ \since 5.2
+*/
+
+int QSpinBox::displayIntegerBase() const
+{
+ Q_D(const QSpinBox);
+ return d->displayIntegerBase;
+}
+
+void QSpinBox::setDisplayIntegerBase(int base)
+{
+ Q_D(QSpinBox);
+ // Falls back to base 10 on invalid bases (like QString)
+ if (base < 2 || base > 36) {
+ qWarning("QSpinBox::setDisplayIntegerBase: Invalid base (%d)", base);
+ base = 10;
+ }
+
+ if (base != d->displayIntegerBase) {
+ d->displayIntegerBase = base;
+ d->updateEdit();
+ }
+}
+
+/*!
This virtual function is used by the spin box whenever it needs to
display the given \a value. The default implementation returns a
string containing \a value printed in the standard way using
@@ -444,9 +478,18 @@ void QSpinBox::setRange(int minimum, int maximum)
QString QSpinBox::textFromValue(int value) const
{
- QString str = locale().toString(value);
- if (qAbs(value) >= 1000 || value == INT_MIN) {
- str.remove(locale().groupSeparator());
+ Q_D(const QSpinBox);
+ QString str;
+
+ if (d->displayIntegerBase != 10) {
+ str = QString::number(qAbs(value), d->displayIntegerBase);
+ if (value < 0)
+ str.prepend('-');
+ } else {
+ str = locale().toString(value);
+ if (qAbs(value) >= 1000 || value == INT_MIN) {
+ str.remove(locale().groupSeparator());
+ }
}
return str;
@@ -926,6 +969,7 @@ QSpinBoxPrivate::QSpinBoxPrivate()
minimum = QVariant((int)0);
maximum = QVariant((int)99);
value = minimum;
+ displayIntegerBase = 10;
singleStep = QVariant((int)1);
type = QVariant::Int;
}
@@ -1003,11 +1047,15 @@ QVariant QSpinBoxPrivate::validateAndInterpret(QString &input, int &pos,
state = QValidator::Invalid; // special-case -0 will be interpreted as 0 and thus not be invalid with a range from 0-100
} else {
bool ok = false;
- num = locale.toInt(copy, &ok);
- if (!ok && copy.contains(locale.groupSeparator()) && (max >= 1000 || min <= -1000)) {
- QString copy2 = copy;
- copy2.remove(locale.groupSeparator());
- num = locale.toInt(copy2, &ok);
+ if (displayIntegerBase != 10) {
+ num = copy.toInt(&ok, displayIntegerBase);
+ } else {
+ num = locale.toInt(copy, &ok);
+ if (!ok && copy.contains(locale.groupSeparator()) && (max >= 1000 || min <= -1000)) {
+ QString copy2 = copy;
+ copy2.remove(locale.groupSeparator());
+ num = locale.toInt(copy2, &ok);
+ }
}
QSBDEBUG() << __FILE__ << __LINE__<< "num is set to" << num;
if (!ok) {
diff --git a/src/widgets/widgets/qspinbox.h b/src/widgets/widgets/qspinbox.h
index 4963f87a1a..98e809e141 100644
--- a/src/widgets/widgets/qspinbox.h
+++ b/src/widgets/widgets/qspinbox.h
@@ -61,6 +61,7 @@ class Q_WIDGETS_EXPORT QSpinBox : public QAbstractSpinBox
Q_PROPERTY(int maximum READ maximum WRITE setMaximum)
Q_PROPERTY(int singleStep READ singleStep WRITE setSingleStep)
Q_PROPERTY(int value READ value WRITE setValue NOTIFY valueChanged USER true)
+ Q_PROPERTY(int displayIntegerBase READ displayIntegerBase WRITE setDisplayIntegerBase)
public:
explicit QSpinBox(QWidget *parent = 0);
@@ -87,6 +88,8 @@ public:
void setRange(int min, int max);
+ int displayIntegerBase() const;
+ void setDisplayIntegerBase(int base);
protected:
bool event(QEvent *event);
diff --git a/src/widgets/widgets/qsplashscreen.cpp b/src/widgets/widgets/qsplashscreen.cpp
index 746c02e4e2..b2a0d3f8b8 100644
--- a/src/widgets/widgets/qsplashscreen.cpp
+++ b/src/widgets/widgets/qsplashscreen.cpp
@@ -200,7 +200,7 @@ void QSplashScreen::repaint()
is kept up to date with what your application is doing (e.g.,
loading files).
- \sa Qt::Alignment, clearMessage()
+ \sa Qt::Alignment, clearMessage(), message()
*/
void QSplashScreen::showMessage(const QString &message, int alignment,
const QColor &color)
@@ -214,6 +214,20 @@ void QSplashScreen::showMessage(const QString &message, int alignment,
}
/*!
+ \since 5.2
+
+ Returns the message that is currently displayed on the splash screen.
+
+ \sa showMessage(), clearMessage()
+*/
+
+QString QSplashScreen::message() const
+{
+ Q_D(const QSplashScreen);
+ return d->currStatus;
+}
+
+/*!
Removes the message being displayed on the splash screen
\sa showMessage()
diff --git a/src/widgets/widgets/qsplashscreen.h b/src/widgets/widgets/qsplashscreen.h
index a1af8e45ef..e675c2e7af 100644
--- a/src/widgets/widgets/qsplashscreen.h
+++ b/src/widgets/widgets/qsplashscreen.h
@@ -63,6 +63,7 @@ public:
const QPixmap pixmap() const;
void finish(QWidget *w);
void repaint();
+ QString message() const;
public Q_SLOTS:
void showMessage(const QString &message, int alignment = Qt::AlignLeft,
diff --git a/src/widgets/widgets/qsplitter.cpp b/src/widgets/widgets/qsplitter.cpp
index 031763b80c..1f3646ea6e 100644
--- a/src/widgets/widgets/qsplitter.cpp
+++ b/src/widgets/widgets/qsplitter.cpp
@@ -1404,19 +1404,24 @@ int QSplitter::closestLegalPosition(int pos, int index)
\property QSplitter::opaqueResize
\brief whether resizing is opaque
- Opaque resizing is on by default.
+ The default resize behavior is style dependent (determined by the
+ SH_Splitter_OpaqueResize style hint). However, you can override it
+ by calling setOpaqueResize()
+
+ \sa QStyle::StyleHint
*/
bool QSplitter::opaqueResize() const
{
Q_D(const QSplitter);
- return d->opaque;
+ return d->opaqueResizeSet ? d->opaque : style()->styleHint(QStyle::SH_Splitter_OpaqueResize, 0, this);
}
void QSplitter::setOpaqueResize(bool on)
{
Q_D(QSplitter);
+ d->opaqueResizeSet = true;
d->opaque = on;
}
@@ -1589,7 +1594,7 @@ static const qint32 SplitterMagic = 0xff;
QByteArray QSplitter::saveState() const
{
Q_D(const QSplitter);
- int version = 0;
+ int version = 1;
QByteArray data;
QDataStream stream(&data, QIODevice::WriteOnly);
@@ -1605,6 +1610,7 @@ QByteArray QSplitter::saveState() const
stream << qint32(handleWidth());
stream << opaqueResize();
stream << qint32(orientation());
+ stream << d->opaqueResizeSet;
return data;
}
@@ -1627,7 +1633,7 @@ QByteArray QSplitter::saveState() const
bool QSplitter::restoreState(const QByteArray &state)
{
Q_D(QSplitter);
- int version = 0;
+ int version = 1;
QByteArray sd = state;
QDataStream stream(&sd, QIODevice::ReadOnly);
QList<int> list;
@@ -1638,7 +1644,7 @@ bool QSplitter::restoreState(const QByteArray &state)
stream >> marker;
stream >> v;
- if (marker != SplitterMagic || v != version)
+ if (marker != SplitterMagic || v > version)
return false;
stream >> list;
@@ -1657,6 +1663,9 @@ bool QSplitter::restoreState(const QByteArray &state)
setOrientation(Qt::Orientation(i));
d->doResize();
+ if (v >= 1)
+ stream >> d->opaqueResizeSet;
+
return true;
}
diff --git a/src/widgets/widgets/qsplitter_p.h b/src/widgets/widgets/qsplitter_p.h
index f1e050b8f6..0d0e134f58 100644
--- a/src/widgets/widgets/qsplitter_p.h
+++ b/src/widgets/widgets/qsplitter_p.h
@@ -83,7 +83,7 @@ class QSplitterPrivate : public QFramePrivate
Q_DECLARE_PUBLIC(QSplitter)
public:
QSplitterPrivate() : rubberBand(0), opaque(true), firstShow(true),
- childrenCollapsible(true), compatMode(false), handleWidth(-1), blockChildAdd(false) {}
+ childrenCollapsible(true), compatMode(false), handleWidth(-1), blockChildAdd(false), opaqueResizeSet(false) {}
QPointer<QRubberBand> rubberBand;
mutable QList<QSplitterLayoutStruct *> list;
@@ -94,6 +94,7 @@ public:
bool compatMode : 8;
int handleWidth;
bool blockChildAdd;
+ bool opaqueResizeSet;
inline int pick(const QPoint &pos) const
{ return orient == Qt::Horizontal ? pos.x() : pos.y(); }
diff --git a/src/widgets/widgets/qtabbar.cpp b/src/widgets/widgets/qtabbar.cpp
index b975035dcf..aa7677869c 100644
--- a/src/widgets/widgets/qtabbar.cpp
+++ b/src/widgets/widgets/qtabbar.cpp
@@ -329,6 +329,26 @@ void QTabBar::initStyleOption(QStyleOptionTab *option, int tabIndex) const
\sa moveTab()
*/
+/*!
+ \fn void QTabBar::tabBarClicked(int index)
+
+ This signal is emitted when user clicks on a tab at an \a index.
+
+ \a index is the index of a clicked tab, or -1 if no tab is under the cursor.
+
+ \since 5.2
+*/
+
+/*!
+ \fn void QTabBar::tabBarDoubleClicked(int index)
+
+ This signal is emitted when the user double clicks on a tab at \a index.
+
+ \a index refers to the tab clicked, or -1 if no tab is under the cursor.
+
+ \since 5.2
+*/
+
int QTabBarPrivate::extraWidth() const
{
Q_Q(const QTabBar);
@@ -1703,11 +1723,37 @@ void QTabBarPrivate::moveTab(int index, int offset)
q_func()->update();
}
+
+/*!
+ \reimp
+*/
+void QTabBar::mouseDoubleClickEvent(QMouseEvent *event)
+{
+ Q_D(QTabBar);
+
+ const QPoint pos = event->pos();
+ const bool isEventInCornerButtons = (!d->leftB->isHidden() && d->leftB->geometry().contains(pos))
+ || (!d->rightB->isHidden() && d->rightB->geometry().contains(pos));
+ if (!isEventInCornerButtons) {
+ const int index = tabAt(pos);
+ emit tabBarDoubleClicked(index);
+ }
+}
+
/*!\reimp
*/
void QTabBar::mousePressEvent(QMouseEvent *event)
{
Q_D(QTabBar);
+
+ const QPoint pos = event->pos();
+ const bool isEventInCornerButtons = (!d->leftB->isHidden() && d->leftB->geometry().contains(pos))
+ || (!d->rightB->isHidden() && d->rightB->geometry().contains(pos));
+ if (!isEventInCornerButtons) {
+ const int index = d->indexAtPos(pos);
+ emit tabBarClicked(index);
+ }
+
if (event->button() != Qt::LeftButton) {
event->ignore();
return;
diff --git a/src/widgets/widgets/qtabbar.h b/src/widgets/widgets/qtabbar.h
index 72c19ab520..1f7b8f6b03 100644
--- a/src/widgets/widgets/qtabbar.h
+++ b/src/widgets/widgets/qtabbar.h
@@ -173,6 +173,8 @@ Q_SIGNALS:
void currentChanged(int index);
void tabCloseRequested(int index);
void tabMoved(int from, int to);
+ void tabBarClicked(int index);
+ void tabBarDoubleClicked(int index);
protected:
virtual QSize tabSizeHint(int index) const;
@@ -186,6 +188,7 @@ protected:
void showEvent(QShowEvent *);
void hideEvent(QHideEvent *);
void paintEvent(QPaintEvent *);
+ void mouseDoubleClickEvent(QMouseEvent *);
void mousePressEvent (QMouseEvent *);
void mouseMoveEvent (QMouseEvent *);
void mouseReleaseEvent (QMouseEvent *);
diff --git a/src/widgets/widgets/qtabbar_p.h b/src/widgets/widgets/qtabbar_p.h
index 7468144146..8c6e70b8d7 100644
--- a/src/widgets/widgets/qtabbar_p.h
+++ b/src/widgets/widgets/qtabbar_p.h
@@ -138,6 +138,10 @@ public:
} *animation;
void startAnimation(QTabBarPrivate *priv, int duration) {
+ if (!priv->isAnimated()) {
+ priv->moveTabFinished(priv->tabList.indexOf(*this));
+ return;
+ }
if (!animation)
animation = new TabBarAnimation(this, priv);
animation->setStartValue(dragOffset);
@@ -162,6 +166,7 @@ public:
int indexAtPos(const QPoint &p) const;
+ inline bool isAnimated() const { Q_Q(const QTabBar); return q->style()->styleHint(QStyle::SH_Widget_Animate, 0, q); }
inline bool validIndex(int index) const { return index >= 0 && index < tabList.count(); }
void setCurrentNextEnabledIndex(int offset);
diff --git a/src/widgets/widgets/qtabwidget.cpp b/src/widgets/widgets/qtabwidget.cpp
index 4df55e2537..9d14c01490 100644
--- a/src/widgets/widgets/qtabwidget.cpp
+++ b/src/widgets/widgets/qtabwidget.cpp
@@ -172,6 +172,26 @@ QT_BEGIN_NAMESPACE
\sa setTabsClosable()
*/
+/*!
+ \fn void QTabWidget::tabBarClicked(int index)
+
+ This signal is emitted when user clicks on a tab at an \a index.
+
+ \a index refers to the tab clicked, or -1 if no tab is under the cursor.
+
+ \since 5.2
+*/
+
+/*!
+ \fn void QTabWidget::tabBarDoubleClicked(int index)
+
+ This signal is emitted when the user double clicks on a tab at an \a index.
+
+ \a index is the index of a clicked tab, or -1 if no tab is under the cursor.
+
+ \since 5.2
+*/
+
class QTabWidgetPrivate : public QWidgetPrivate
{
Q_DECLARE_PUBLIC(QTabWidget)
@@ -693,6 +713,10 @@ void QTabWidget::setTabBar(QTabBar* tb)
this, SLOT(_q_showTab(int)));
connect(d->tabs, SIGNAL(tabMoved(int,int)),
this, SLOT(_q_tabMoved(int,int)));
+ connect(d->tabs, SIGNAL(tabBarClicked(int)),
+ this, SIGNAL(tabBarClicked(int)));
+ connect(d->tabs, SIGNAL(tabBarDoubleClicked(int)),
+ this, SIGNAL(tabBarDoubleClicked(int)));
if (d->tabs->tabsClosable())
connect(d->tabs, SIGNAL(tabCloseRequested(int)),
this, SIGNAL(tabCloseRequested(int)));
diff --git a/src/widgets/widgets/qtabwidget.h b/src/widgets/widgets/qtabwidget.h
index 1a1eb2ef2b..83c2e31d28 100644
--- a/src/widgets/widgets/qtabwidget.h
+++ b/src/widgets/widgets/qtabwidget.h
@@ -151,6 +151,8 @@ public Q_SLOTS:
Q_SIGNALS:
void currentChanged(int index);
void tabCloseRequested(int index);
+ void tabBarClicked(int index);
+ void tabBarDoubleClicked(int index);
protected:
virtual void tabInserted(int index);
diff --git a/src/widgets/widgets/qtextedit.cpp b/src/widgets/widgets/qtextedit.cpp
index 4b3bf6de65..4e0c682493 100644
--- a/src/widgets/widgets/qtextedit.cpp
+++ b/src/widgets/widgets/qtextedit.cpp
@@ -773,6 +773,35 @@ QTextDocument *QTextEdit::document() const
}
/*!
+ \since 5.2
+
+ \property QTextEdit::placeholderText
+ \brief the editor placeholder text
+
+ Setting this property makes the editor display a grayed-out
+ placeholder text as long as the document() is empty.
+
+ By default, this property contains an empty string.
+
+ \sa document()
+*/
+QString QTextEdit::placeholderText() const
+{
+ Q_D(const QTextEdit);
+ return d->placeholderText;
+}
+
+void QTextEdit::setPlaceholderText(const QString &placeholderText)
+{
+ Q_D(QTextEdit);
+ if (d->placeholderText != placeholderText) {
+ d->placeholderText = placeholderText;
+ if (d->control->document()->isEmpty())
+ d->viewport->update();
+ }
+}
+
+/*!
Sets the visible \a cursor.
*/
void QTextEdit::setTextCursor(const QTextCursor &cursor)
@@ -1499,6 +1528,13 @@ void QTextEdit::paintEvent(QPaintEvent *e)
Q_D(QTextEdit);
QPainter p(d->viewport);
d->paint(&p, e);
+ if (!d->placeholderText.isEmpty() && d->control->document()->isEmpty()) {
+ QColor col = palette().text().color();
+ col.setAlpha(128);
+ p.setPen(col);
+ const int margin = int(document()->documentMargin());
+ p.drawText(d->viewport->rect().adjusted(margin, margin, -margin, -margin), Qt::AlignTop | Qt::TextWordWrap, d->placeholderText);
+ }
}
void QTextEditPrivate::_q_currentCharFormatChanged(const QTextCharFormat &fmt)
diff --git a/src/widgets/widgets/qtextedit.h b/src/widgets/widgets/qtextedit.h
index e1471848e7..06ec5fb889 100644
--- a/src/widgets/widgets/qtextedit.h
+++ b/src/widgets/widgets/qtextedit.h
@@ -85,6 +85,7 @@ class Q_WIDGETS_EXPORT QTextEdit : public QAbstractScrollArea
Q_PROPERTY(int cursorWidth READ cursorWidth WRITE setCursorWidth)
Q_PROPERTY(Qt::TextInteractionFlags textInteractionFlags READ textInteractionFlags WRITE setTextInteractionFlags)
Q_PROPERTY(QTextDocument *document READ document WRITE setDocument DESIGNABLE false)
+ Q_PROPERTY(QString placeholderText READ placeholderText WRITE setPlaceholderText)
public:
enum LineWrapMode {
NoWrap,
@@ -108,6 +109,9 @@ public:
void setDocument(QTextDocument *document);
QTextDocument *document() const;
+ void setPlaceholderText(const QString &placeholderText);
+ QString placeholderText() const;
+
void setTextCursor(const QTextCursor &cursor);
QTextCursor textCursor() const;
diff --git a/src/widgets/widgets/qtextedit_p.h b/src/widgets/widgets/qtextedit_p.h
index 1ce68dc23e..daa6eb5ed0 100644
--- a/src/widgets/widgets/qtextedit_p.h
+++ b/src/widgets/widgets/qtextedit_p.h
@@ -130,6 +130,8 @@ public:
QString anchorToScrollToWhenVisible;
+ QString placeholderText;
+
#ifdef QT_KEYPAD_NAVIGATION
QBasicTimer deleteAllTimer;
#endif
diff --git a/src/widgets/widgets/qwidgetanimator.cpp b/src/widgets/widgets/qwidgetanimator.cpp
index bbd96ca29a..1209ade536 100644
--- a/src/widgets/widgets/qwidgetanimator.cpp
+++ b/src/widgets/widgets/qwidgetanimator.cpp
@@ -91,24 +91,28 @@ void QWidgetAnimator::animate(QWidget *widget, const QRect &_final_geometry, boo
QRect(QPoint(-500 - widget->width(), -500 - widget->height()), widget->size());
#ifndef QT_NO_ANIMATION
- AnimationMap::const_iterator it = m_animation_map.constFind(widget);
- if (it != m_animation_map.constEnd() && (*it)->endValue().toRect() == final_geometry)
- return;
+ //If the QStyle has animations, animate
+ if (widget->style()->styleHint(QStyle::SH_Widget_Animate, 0, widget)) {
+ AnimationMap::const_iterator it = m_animation_map.constFind(widget);
+ if (it != m_animation_map.constEnd() && (*it)->endValue().toRect() == final_geometry)
+ return;
- QPropertyAnimation *anim = new QPropertyAnimation(widget, "geometry", widget);
- anim->setDuration(animate ? 200 : 0);
- anim->setEasingCurve(QEasingCurve::InOutQuad);
- anim->setEndValue(final_geometry);
- m_animation_map[widget] = anim;
- connect(anim, SIGNAL(finished()), SLOT(animationFinished()));
- anim->start(QPropertyAnimation::DeleteWhenStopped);
-#else
+ QPropertyAnimation *anim = new QPropertyAnimation(widget, "geometry", widget);
+ anim->setDuration(animate ? 200 : 0);
+ anim->setEasingCurve(QEasingCurve::InOutQuad);
+ anim->setEndValue(final_geometry);
+ m_animation_map[widget] = anim;
+ connect(anim, SIGNAL(finished()), SLOT(animationFinished()));
+ anim->start(QPropertyAnimation::DeleteWhenStopped);
+ } else
+#endif //QT_NO_ANIMATION
+ {
//we do it in one shot
widget->setGeometry(final_geometry);
#ifndef QT_NO_MAINWINDOW
m_mainWindowLayout->animationFinished(widget);
#endif //QT_NO_MAINWINDOW
-#endif //QT_NO_ANIMATION
+ }
}
bool QWidgetAnimator::animating() const
diff --git a/src/widgets/widgets/qwidgetlinecontrol.cpp b/src/widgets/widgets/qwidgetlinecontrol.cpp
index 9212f942c5..d10001a305 100644
--- a/src/widgets/widgets/qwidgetlinecontrol.cpp
+++ b/src/widgets/widgets/qwidgetlinecontrol.cpp
@@ -427,7 +427,7 @@ bool QWidgetLineControl::fixup() // this function assumes that validate currentl
m_validator->fixup(textCopy);
if (m_validator->validate(textCopy, cursorCopy) == QValidator::Acceptable) {
if (textCopy != m_text || cursorCopy != m_cursor)
- internalSetText(textCopy, cursorCopy);
+ internalSetText(textCopy, cursorCopy, false);
return true;
}
}
@@ -672,7 +672,7 @@ bool QWidgetLineControl::finishChange(int validateFromState, bool update, bool e
m_validInput = (m_validator->validate(textCopy, cursorCopy) != QValidator::Invalid);
if (m_validInput) {
if (m_text != textCopy) {
- internalSetText(textCopy, cursorCopy);
+ internalSetText(textCopy, cursorCopy, false);
return true;
}
m_cursor = cursorCopy;
diff --git a/src/widgets/widgets/qwidgettextcontrol.cpp b/src/widgets/widgets/qwidgettextcontrol.cpp
index de06d4454a..0255183c87 100644
--- a/src/widgets/widgets/qwidgettextcontrol.cpp
+++ b/src/widgets/widgets/qwidgettextcontrol.cpp
@@ -2126,6 +2126,13 @@ void QWidgetTextControlPrivate::editFocusEvent(QEvent *e)
#endif
#ifndef QT_NO_CONTEXTMENU
+static inline void setActionIcon(QAction *action, const QString &name)
+{
+ const QIcon icon = QIcon::fromTheme(name);
+ if (!icon.isNull())
+ action->setIcon(icon);
+}
+
QMenu *QWidgetTextControl::createStandardContextMenu(const QPointF &pos, QWidget *parent)
{
Q_D(QWidgetTextControl);
@@ -2145,17 +2152,21 @@ QMenu *QWidgetTextControl::createStandardContextMenu(const QPointF &pos, QWidget
if (d->interactionFlags & Qt::TextEditable) {
a = menu->addAction(tr("&Undo") + ACCEL_KEY(QKeySequence::Undo), this, SLOT(undo()));
a->setEnabled(d->doc->isUndoAvailable());
+ setActionIcon(a, QStringLiteral("edit-undo"));
a = menu->addAction(tr("&Redo") + ACCEL_KEY(QKeySequence::Redo), this, SLOT(redo()));
a->setEnabled(d->doc->isRedoAvailable());
+ setActionIcon(a, QStringLiteral("edit-redo"));
menu->addSeparator();
a = menu->addAction(tr("Cu&t") + ACCEL_KEY(QKeySequence::Cut), this, SLOT(cut()));
a->setEnabled(d->cursor.hasSelection());
+ setActionIcon(a, QStringLiteral("edit-cut"));
}
if (showTextSelectionActions) {
a = menu->addAction(tr("&Copy") + ACCEL_KEY(QKeySequence::Copy), this, SLOT(copy()));
a->setEnabled(d->cursor.hasSelection());
+ setActionIcon(a, QStringLiteral("edit-copy"));
}
if ((d->interactionFlags & Qt::LinksAccessibleByKeyboard)
@@ -2169,9 +2180,11 @@ QMenu *QWidgetTextControl::createStandardContextMenu(const QPointF &pos, QWidget
#if !defined(QT_NO_CLIPBOARD)
a = menu->addAction(tr("&Paste") + ACCEL_KEY(QKeySequence::Paste), this, SLOT(paste()));
a->setEnabled(canPaste());
+ setActionIcon(a, QStringLiteral("edit-paste"));
#endif
a = menu->addAction(tr("Delete"), this, SLOT(_q_deleteSelected()));
a->setEnabled(d->cursor.hasSelection());
+ setActionIcon(a, QStringLiteral("edit-delete"));
}