Qt project org faq

From Qt Wiki
Jump to: navigation, search

This page contains the technical FAQs that were at hosted at http://qt-project/faq/

The FAQs have accumulated over a long time period and some of the content may not apply to the latest releases. Please be aware of this when you apply them to the latest builds of Qt.

Contents

When to use QPluginLoader vs QLibrary when splitting code into several dlls?

QPluginLoader http://doc.qt.io/qt-5/latest/qpluginloader.html offers an advantage over QLibrary http://doc.qt.io/qt-5/latest/qlibrary.html because it checks that the plugin is linked against the same version of Qt as the application. QLibrary will not do this check for you. If the library is Qt based and only used within a Qt application then this is probably the best approach. See the documentation http://doc.qt.io/qt-5/plugins-howto.html on how to create plugins.

If you want to make the dlls usable with other applications, then you will need to use QLibrary and create the library as a normal C++ library.

The plugin approach is generally the easier one to set up and use as you can drop in more plugins into the application without too much of a problem.

Finally, in order to break up your code into several dll's, you could simply create shared libraries that you link against, see:

http://doc.qt.io/sharedlibrary,html

What is the process for contributing to Qt?

The contribution guidelines are detailed on this wiki page(Contribution guidelines) http://wiki.qt.io/Qt-Contribution-Guidelines

(Answer updated May 2014)

How can I invoke functions on QObjects from another thread?

There are a two basic methods for calling a function from one thread on a QObject in another thread.

How can I rotate items in a QGraphicsView using the mouse?

You can rotate items in a QGraphicsView http://doc.qt.io/qt-5/qgraphicsview.html using the mouse by reimplementing the mousePressEvent() http://doc.qt.io/qt-5/qgraphicsitem.html#mousePressEvent and mouseMoveEvent() http://doc.qt.io/qt-5/qgraphicsitem.html#mouseMoveEvent for the items. In the mousePressEvent() you can store the position for the mouse press and use that in the mouseMoveEvent() in order to calculate the value for the rotation. The rotation can then be set in the mouseMoveEvent() either by creating a QTransform http://doc.qt.io/qt-5/qtransform.html and calling setTransform() http://doc.qt.io/qt-5/qgraphicsitem.html#setTransform on the item or by calling setRotation() http://doc.qt.io/qt-5/qgraphicsitem.html#setRotation on the item.

The example below illustrates how this can be done:

#include <QtGui>
 
class GraphicsEllipseItem : public QGraphicsEllipseItem
{
public:
  GraphicsEllipseItem()
 
  {
    rotation = 0;
    setFlags(flags() | QGraphicsItem::ItemIsSelectable);
  }
 
  void mousePressEvent(QGraphicsSceneMouseEvent *event)
  {
    initialPos = mapToScene(event->pos());
    QGraphicsItem::mousePressEvent(event);
  }
 
  void mouseMoveEvent(QGraphicsSceneMouseEvent *event)
  {
    QPointF pos = mapToScene(event->pos());
 
    if (pos.y() > initialPos.y()) {
      ++rotation;
    } else {
      --rotation;
    }
 
#if 1
    QTransform xform;
    xform.rotate(rotation);
    setTransform(xform);
#else
    setRotation(rotation);
#endif
    initialPos = pos;
  }
  QPointF initialPos;
  qreal rotation;
 
};
 
 
class GraphicsView : public QGraphicsView
{
public:
  GraphicsView()
  {
    QGraphicsScene *scene = new QGraphicsScene();
    setScene(scene);
    QRect rectangle(10, 20, 80, 60);
    QRect rectangle2(50, 80, 80, 60);
 
 
    GraphicsEllipseItem *item1 = new GraphicsEllipseItem();
    item1->setRect(-40, -30, 80, 60);
    scene->addItem(item1);
  }
};
 
int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  GraphicsView box;
  box.show();
  return app.exec();    
}

The Makefile generated by the Qt Eclipse Integration has no 'dist' target. Is it really missing?

You find dist targets in both the generated Makefile.Debug and Makefile.Release. You can create an Eclipse Make Target with target 'dist' and build command 'make -f Makefile.Release' to use it from Eclipse.


Why is Qt released under LGPL?

The LGPL license will make it easier for developers to adopt Qt. By spreading the use of Qt as widely as possible and establishing a robust ecosystem.


How can I make the non-slot and non-property members of an object available to the script engine?

By default only a QObject's http://doc.qt.io/qt-5/latest/qobject.html signals, slots, properties, and child objects are available to scripts when a QObject is passed to the QScriptEngine's newQObject() http://doc.qt.io/qt-5/qscriptengine.html#newQObject function.

In order to make other members of the class available to the engine you can use one of the following approaches:

  1. Create a binding for it yourself, for example by creating your own object that calls the relevant function in a slot.
  2. Use newFunction() http://doc.qt.io/qt-5/qscriptengine.html#newFunction
  3. Use the Qt Script Generator http://labs.trolltech.com/blogs/2008/03/10/bind-aid/ that generates Qt bindings for Qt Script, see:



How can I trigger the parent widget to resize when its child widget is resized programmatically?

It is the job of the layout to determine the size and position of the widgets. So if you explicitly resize a child widget which is inside a layout, you need to ensure that the new size is passed correctly through the layout system. This can be done by ensuring that the widget's sizeHint() http://doc.qt.io/qt-5/qwidget.html#sizeHint-prop returns the new size. The value returned by the sizeHint() will be used when the layout calculates the new size. So after the sizeHint() has changed, simply call updateGeometry() http://doc.qt.io/qt-5/qwidget.html#updateGeometry that will notify the layout system that the widget has changed and may need to change geometry.

An alternative way to ensure that the parent widget is resized in response to its child being resized, is to call setFixedSize() http://doc.qt.io/qt-5/qwidget.html#setFixedSize on the child.

The following example illustrates how this can be done:

#include <QtGui>  
 
class Label : public QLabel 
{  
    Q_OBJECT 
public:
    Label(const QString & text, QWidget * parent) : QLabel(text, parent)  
    {
        changeSize = false;   
        setAutoFillBackground(true);   
        QPalette pal = palette();
        pal.setColor(QPalette::Window, Qt::red);   
        setPalette(pal);  
    }   
 
    QSize sizeHint() const  
    {   
        if(changeSize) {    
            return QSize(400,400);   
        } else {
            return QLabel::sizeHint();
        }  
    }   
 
    void setChangedSize(bool value)  
    {
        changeSize = value;  
    }  
 
private:  
    bool changeSize;   
}; 
 
class Widget : public QWidget 
{  
    Q_OBJECT  
public:  
    Widget()  
    {   
        label = new Label("Hello World", this);    
        QLabel *label2 = new QLabel("Standard label", this);
        label2->setAutoFillBackground(true);   
        QPalette pal = label2->palette();
        pal.setColor(QPalette::Window, Qt::blue);   
        label2->setPalette(pal);
        QVBoxLayout *layout = new QVBoxLayout(this);   
        layout->addWidget(label);
        layout->addWidget(label2);   
        QTimer::singleShot(2000, this, SLOT(testSlot()));
    }  
 
public slots:   
    void testSlot()   
    { 
#if 0    
        label->setFixedSize(400,400);
#else    
        QSize oldSize = label->size();    
        label->setChangedSize(true);
        if(oldSize.width() < label->sizeHint().width() || 
           oldSize.height() < label->sizeHint().height()) {     
            label->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);     
            label->updateGeometry();
        } else {
            label->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
            label->updateGeometry();
        } 
#endif   
    } 
private:  
    Label *label;  
};  
 
#include "main.moc" 
 
int main(int argc, char **argv)
{  
    QApplication app(argc, argv);
    Widget widget;  
    widget.resize(200,200);  
    widget.show();  
    return app.exec();
}

Assistant does not launch or the documentation does not show up when launching Assistant, what is wrong?

Deleting the following Qt Assistant http://doc.qt.io/qt-5/latest/assistant-manual.html key in the registry might solve the problem:

  • HKEY_CURRENT_USER\SOFTWARE\Trolltech\Qt Assistant*


When I set a font/palette explicitly for a QLabel on the Mac, then it is respected. If my QLabel only inherits the font, then it is ignored. What is the reason for this?

This is the expected behavior. Qt/Mac tries to set widget specific fonts and palettes for certain widgets at startup and also when the application gains focus. Unless you specify the font or palette explicitly yourself for a widget then the system font will override your font settings. You can avoid this behavior by calling setDesktopSettingsAware() http://doc.qt.io/qt-5/qapplication.html#setDesktopSettingsAware with false as an argument first in your application.

When in doubt, set the font or palette directly.


How can a menu be removed from a menubar?

You can remove actions from the menubar using QWidget::removeAction() http://doc.qt.io/qt-5/qwidget.html#removeAction.

In order to get hold of the action associated with the menu, use QMenu::menuAction() http://doc.qt.io/qt-5/qmenu.html#menuAction

The example below demonstrates how this can be done:

#include <QtGui>  
 
class MainWindow : public QMainWindow 
{ 
public:
    MainWindow()
    {   
        QMenu *menu = menuBar()->addMenu("Test");   
        QMenu *menu2 = menuBar()->addMenu("Test2");   
        menu->addAction("First");
        menu2->addAction("Second");   
        menuBar()->removeAction(menu->menuAction());
    } 
};  
 
int main(int argc, char **argv) 
{     
    QApplication app(argc, argv);
    MainWindow box;     
    box.show();     
    return app.exec();     
}

How can I get/set the max length of a QTextEdit ?

There is no direct API to set/get a maximum length of a QTextEdit, but you can handle this yourself by connecting a slot to the contentsChanged() http://doc.qt.io/qt-5/qtextdocument.html#contentsChanged signal and then call toPlainText().length() http://doc.qt.io/qt-5/qtextdocument.html#toPlainText to find out how big it is. If it is up to the limit then you can reimplement keyPressEvent() http://doc.qt.io/qt-5/latest/qtextedit.html#keyPressEvent and keyReleaseEvent() http://doc.qt.io/qt-5/latest/qtextedit.html#keyReleaseEvent to do nothing for normal characters.




Lines with width 1 disappear when not using anti-aliasing

When having a transformation set and not using anti-aliasing then if you draw something that's smaller than a pixel, you are not guaranteed that it will get drawn. In order to guarantee that it shows up you need to either turn on anti-aliasing or draw using a cosmetic pen.


Should one use qApp or QCoreApplication::instance() when referring to the application object?

It does not matter which one you use. The instance() http://doc.qt.io/qt-5/latest/qcoreapplication.html#instance function was added since many feel using a function and not a global variable is more elegant, qApp http://doc.qt.io/qt-5/latest/qapplication.html#qApp is kept for compatibility reasons and for those who prefer global pointers


When QHttp::post() is called it doesn't seem to post a request, what is going wrong?

There are potentially two problems here that is causing this to happen. One is that the URL you are attempting to post to does not actually accept a POST request. If this is not the case and it should be accepting POST requests then it is because QHttp::post() http://doc.qt.io/qt-5/latest/qhttp.html#post does not set a content-type for the request. Subsequently the server is ignoring the post request. In order to resolve this using QHttp, then the solution is to use request() http://doc.qt.io/qt-5/latest/qhttp.html#request instead.

The following is an example which queries http://www.rootsweb.com for all matches for the name John Smith

#include <QtGui> 
#include <QtNetwork>  
 
class MyHttp : public QHttp 
{
    Q_OBJECT 
public:     
    MyHttp(const QString &host) : QHttp(host)     
    {
        connect(this, SIGNAL(requestFinished(int, bool)), this, SLOT(finished(int, bool)));
        f.setFileName("results.html");
        f.open(QIODevice::WriteOnly | QIODevice::Truncate);         
        QByteArray inputStr("given=John&surname=Smith");         
        QHttpRequestHeader header("POST", "/cgi-bin/metasearch");
        header.setValue("Content-Type", "application/x-www-form-urlencoded");
        header.setValue("Host", "resources.rootsweb.com");
        request(header,inputStr,&f);     
    } 
 
public slots:     
    void finished(int id, bool error)     
    {         
        if (error) {
            qDebug("Failed with an error");             
            return;         
        }
        f.close();         
        QFile f2("results.html");
        f2.open(QIODevice::ReadOnly);         
        emit updateContents(f2.readAll());
    }
 
signals:     
    void updateContents(const QString &text); 
 
private:     
    QFile f;
};  
 
#include "main.moc"  
 
int main(int argc, char **argv) 
{     
    QApplication a(argc, argv);     
    MyHttp http("resources.rootsweb.com");     
    QTextEdit te;
    te.show();    
    QObject::connect(&http, SIGNAL(updateContents(const QString &)),
                     &te, SLOT(setHtml(const QString &)));
    return a.exec(); 
}

The key thing here is to look at the QHttpRequestHeader and construct the request in a similar way, the input string is the actual variables being sent using name-value pairs. For more information, then see:

http://doc.qt.io/qt-5/qhttp.html http://doc.qt.io/qt-5/qhttprequestheader.html


When keeping a key pressed down, then I receive a number of keyReleaseEvents() in addition to keyPressEvents(). Why is this happening and what can be done to only get a mousePressEvent() ?

When a given key is continuously pressed it results in a continuous stream of events for the associated key. You will get both keyPressEvents() http://doc.qt.io/qt-5/latest/qwidget.html#keyPressEvent and keyReleaseEvents() http://doc.qt.io/qt-5/latest/qwidget.html#keyReleaseEvent for the relevant key even if you have not released the key. You can not stop the events from being sent since they come directly from the windowing system. What you can do however is to check the autoRepeat() http://doc.qt.io/qt-5/qkeyevent.html#isAutoRepeat function in your key event handler and just ignore the key event if it was generated by an auto-repeating key.

See the following example for an illustration:

#include <QtGui>  
 
class Widget : public QWidget
{ 
public:  
    Widget() 
    {
        setFocusPolicy(Qt::StrongFocus);  
    }  
 
    void keyPressEvent(QKeyEvent *event)  
    {
        if(event->isAutoRepeat() ) {    
            qDebug() << "keyPressEvent ignore";
            event->ignore();   
        } else {    
            qDebug() << "keyPressEvent accept";
            event->accept();
        }  
    }  
 
    void keyReleaseEvent(QKeyEvent *event)  
    {
        if(event->isAutoRepeat() ) {    
            qDebug() << "keyReleaseEvent ignore";
            event->ignore();   
        } else {    
            qDebug() << "keyReleaseEvent accept";
            event->accept(); 
        } 
    } 
};  
 
int main(int argc, char **argv) 
{  
    QApplication app(argc, argv);  
    Widget box;  
    box.show();  
    return app.exec();     
}

How can I get a handle to a pixmap in the form of a CoreGraphics surface/pointer on Mac?

You can use the macCGHandle() http://doc.qt.io/qt-5/latest/qwidget.html#macCGHandle function which will return a CGImageRef and the macQDHandle() http://doc.qt.io/qt-5/latest/qwidget.html#macQDHandle function which will return a gworld pointer. See qpixmap.h for the definitions of these functions.


How can I capture events for the delegate in my own class?

It is not possible to capture events for the delegate in a custom class. You need to reimplement the eventFilter() http://doc.qt.io/qt-5/latest/qstyleditemdelegate.html#eventFilter for the delegate in order to grab its events. This is necessary because the delegate installs an event filter on the editor for the cell after the external event filter is installed, meaning it is always going to get the event first.


How can I ensure that a horizontal scrollbar and not an ellipse shows up when resizing a column smaller than its content in a QTreeView ?

To ensure that a scrollbar shows up instead of an ellipse when resizing a column smaller than its content in a QTreeView http://doc.qt.io/qt-5/latest/qtreeview.html, then you need to call

setResizeMode(relevantColumn, QHeaderView::ResizeToContents)

on the header of your tree, so that the section is resized to its optimal size. You also need to call

setStretchLastSection(false)

if your tree only contains one column.

See the documentation:

http://doc.qt.io/qt-5/qheaderview.html#ResizeMode-enum http://doc.qt.io/qt-5/qheaderview.html#stretchLastSection-prop

See the following example for a demonstration:

#include <QtGui> 
 
int main(int argc, char **argv)
{ 
    QApplication app(argc, argv); 
    QTreeWidget tree; 
    tree.setColumnCount(1);
    tree.header()->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
    tree.header()->setResizeMode(0, QHeaderView::ResizeToContents);
    tree.header()->setStretchLastSection(false); 
    QStringList list;  list << An item in a QTreeWidget with some text; 
    QTreeWidgetItem *item = new QTreeWidgetItem(&tree, list); 
    tree.show(); 
    return 
}

Why doesn't Eclipse know about some of Qt's symbols / class names?

You might need to increase the maximal memory used by CDT's indexer:

  • CDT 4.0: Window->Preferences->C++->Indexer*

and raise the 'Cache limits'.

  • CDT 3.1: Window->Preferences->C++->Parser,*

and raise the 'CodeReader Buffer Size'.

You probably also want to run Eclipse with a higher memory limit, so call eclipse from the command line, with e.g.:

eclipse -vmargs -Xmx1000M


Does Qt provide an API for opening/saving encrypted files?

Qt does not offer encryption for opening/saving files, you will need to use a 3rd party library to manage this.


Example of how to style QToolBox with QStyle

The following is an sample subclass of QWindowsXPStyle() http://doc.qt.io/qt-5/latest/qwindowsxpstyle.html to show how a QToolBox http://doc.qt.io/qt-5/latest/qtoolbox.html can be styled.

#include <QtGui>
 
class MyStyle : public QWindowsXPStyle
{
public:
    MyStyle() : QWindowsXPStyle() {}
    void drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, 
                     const QWidget *widget = 0) const
    {
        if (element == CE_ToolBoxTab) {
            const QStyleOptionToolBox *tb = qstyleoption_cast<const QStyleOptionToolBox *>(option);
            painter->save();
            painter->setBrush(QBrush(Qt::darkBlue));
            painter->drawRoundedRect(option->rect.x() + 10, option->rect.y(), option->rect.width() - 20,
                                     option->rect.height(), 10.0, 5.0);
            painter->setPen(Qt::white);
            painter->drawText(option->rect.x() + 15, option->rect.y() + 15, tb->text);
            painter->restore();
        } else {
            return QWindowsXPStyle::drawControl(element, option, painter, widget);
        }
    }
};
 
int main(int argc, char **argv)
{
    QApplication a(argc, argv);
    a.setStyle(new MyStyle);
    QToolBox tb;
    tb.addItem(new QPushButton("A"), "Test");
    tb.addItem(new QPushButton("B"), "Test 2");
    tb.show();
    return a.exec();
}

How can we create a binary on Leopard that runs on both 10.4 and 10.5?

When creating an application on Leopard , then in order for the application to run on both 10.4 and 10.5 then you need to set the *QMAKE_MACOSX_DEPLOYMENT_TARGET* to 10.4 in your .pro file as follows:

 QMAKE_MACOSX_DEPLOYMENT_TARGET = 10.4

This is documented here http://doc.qt.io/qt-5/deployment-mac.html#mac-os-x-version-dependencies.

Note that if you are using native calls then you will have to add checks yourself to ensure that it works correctly for all versions of the operating system. You can for example use

 QSysInfo::MacintoshVersion < QsysInfo::MV_10_5

or check if the function pointer is non-zero. This will not be necessary when only using the Qt API as Qt does such checks for you.

Note that a Qt application compiled against 10.4 should run fine on 10.5.


My Windows build of Qt stops and complains that one of the plugins can't be opened. What's wrong ?

This problem is most likely related to you having had a previous version of Qt installed or that a Qt application that uses the named plugin is still running. Open the task manager and close down all Qt applications and restart the build. If this does not help, then try deleting the plugin dll explicitly and restart the build. This should solve the problem.


How can I prevent the text in a QComboBox's dropdown from being clipped when the QComboBox is smaller than the text?

To ensure that the text in the QComboBox's http://doc.qt.io/qt-5/latest/qcombobox.html view does not get clipped when the QComboBox is resized to a smaller width than the width of the text in the view, you can call

     view->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);

which stops the view from being smaller than its sizeHint() http://doc.qt.io/qt-5/latest/qcombobox.html#sizeHint. See the documentation on size policies http://doc.qt.io/qt-5/latest/qsizepolicy.html#Policy-enum.

See the following example for a demonstration:

#include <QtGui> 
 
class MyWidget : public QWidget
{
public:
	MyWidget(QWidget *parent)   : QWidget(parent) 
	{  
		QVBoxLayout *layout = new QVBoxLayout(this);  
		QComboBox *combo = new QComboBox(this);
		combo->view()->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
		layout->addWidget(combo, 1, 0);  
		combo->addItem(Combo box entry number 1);
		combo->addItem(Combo box entry number 2);  
		combo->addItem(Combo box entry number 3);  
		setMinimumWidth(5); 
	}
}; 
 
int main( int argc, char **argv )
{
	QApplication app( argc, argv ); 
	MyWidget mw(0); 
	mw.show(); 
	return app.exec();
}

Why does the 'New C++ Class' wizard miss most of the Qt classes in the 'Base Classes' list?

The wizard only provides classes that are known to the indexer - which, by default, only parses headers that are somehow reachable via includes in the projects header and source files. So, to have a Qt class in the 'New C++ Class' wizard you have to either include its header in one of your source or header files, or check the 'Index all files' checkbox in the global or project specific 'Indexer' settings (CDT 4.0 only).


How can I sort a QComboBox?

You can get hold of the combobox's model using model() http://doc.qt.io/qt-5/qcombobox.html#model and then call sort() http://doc.qt.io/qt-5/qabstractitemmodel.html#sort on the model.

Alternatively, you can use a proxy model http://doc.qt.io/qt-5/qsortfilterproxymodel.html.



Which compiler and debugger can I use with the Eclipse C++ Integration on Windows?

The Eclipse Integration for C++ supports both gcc provided with MinGW and cl.exe provided with Visual Studio. The Eclipse CDT plugin only supports gdb as a debugger however, so you have to use gcc as a compiler to be able to debug in Eclipse. For cl.exe it is possible to build release and debug versions in Eclipse, but it will not be possible to debug it.


When using fromWinHBITMAP() to create my pixmaps, they appear with a black background. What's wrong ?

If you pass in QPixmap::NoAlpha http://doc.qt.io/qt-5/latest/qpixmap.html#HBitmapFormat-enum as the format to fromWinHBITMAP() http://doc.qt.io/qt-5/latest/qpixmap.html#fromWinHBITMAP then all pixels with transparency will have an undefined value, for instance black.

If the format you pass in to fromWinHBITMAP() is QPixmap::PremultipliedAlpha option the pixel data must be in a premultiplied alpha format, otherwise the results will be undefined. QPixmap expects opaque pixels to be in the form 0xFFrrggbb, where the alpha byte is set to 255. If your pixels are in the form 0x00rrggbb, having an alpha of 0 then the image will not look correct.

If you created your pixel data using GDI functions its likely that you ended up with pixels in the form 0x00rrggbb as GDI will unset the alpha channel of all pixels it touches. You can work around this by manually patching up the alpha channel, afterwards or by only using GDI functions that support a proper alpha channel, like AlphaBlend.


Is it possible to have transparent Qt widgets on top of a QGLWidget?

Qt provides a way to paint to an OpenGL context, but this is in the end painted separately from Qt and the two painting systems are not synchronized, so Qt cannot compose (semi-)transparent images on top of a QGLWidget. At best, you can have opaque widgets on top of the QGLWidget, but even then you may experience some flicker due to the painting being asynchronous.


Where do I find the resource editor in the integrated Qt Designer when using the Qt Eclipse Integration?

The Qt Eclipse Integration comes with a full editor for resource files. Just double click on the resource file in the Projects view. The integrated Qt Designer doesn't come with an extra resource editor.


Is there a way to make a menu in a QMainWindow that automatically redirects standard commands to the current widget ?

There is no automatic way to redirect the commands in a QMainWindow's http://doc.qt.io/qt-5/latest/qmainwindow.html menu to the current widget. If you would like e.g the Copy command to be redirected to the current widget, then you can listen for the QApplication::focusChanged() http://doc.qt.io/qt-5/qapplication.html#focusChanged signal and connect that signal to a slot which determines which actions should be executed for the current widget.



How do I find out why my mouse and keyboard work in QVFb, but not on my target system?

Keyboard and mouse problems should always be debugged on the Linux frame buffer not in QVFb as QVFb uses X keyboard and mouse drivers.

To debug on the Linux frame buffer, run the application in a console on your desktop system, with the option: -display LinuxFb instead of -display QVFb.


How can I specify the spacing between the text and the icon for an item in a view?

In order to specify the margin between the decoration and the text for an item in a view, you can subclass the style and reimplement pixelMetric() http://doc.qt.io/qt-5/latest/qstyle.html#pixelMetric to return the value you want for PM_FocusFrameHMargin http://doc.qt.io/qt-5/qstyle.html#PixelMetric-enum and/or PM_FocusFrameVMargin. Alternatively, you can reimplement paint() http://doc.qt.io/qt-5/latest/qstyleditemdelegate.html#paint for the item delegate to draw the margins as you want.

The following example demonstrates how this can be done by reimplementing pixelMetric():

#include <QtGui>  
 
class Style: public QWindowsStyle 
{ 
public:  
    Style()  {}  
    int pixelMetric(PixelMetric metric, const QStyleOption *option = 0,
                    const QWidget *widget = 0) const
    {   
        if (metric == PM_FocusFrameHMargin) {
            return 10;   
        } else {    
            return QWindowsStyle::pixelMetric(metric, option, widget);
        }  
    } 
};  
 
int main(int argc, char **argv)
{     
    QApplication app(argc, argv);     
    QTreeWidget tree;     
    tree.setStyle(new Style());
    QPixmap pix(12, 12);     
    pix.fill(Qt::red);     
    QTreeWidgetItem *item1 = new QTreeWidgetItem(&tree);     
    item1->setText(0, "first");     
    item1->setIcon(0, QIcon(pix));     
    QTreeWidgetItem *item2 = new QTreeWidgetItem(&tree);
    item2->setText(0, "second");     
    item2->setIcon(0, QIcon(pix));
    tree.show();     
    return app.exec();
}

Does qmake have support for pkg-config?

Yes, simply add link_pkgconfig to the CONFIG entry in your .pro file and then add pkg-config configurations to the PKGCONFIG variable, e.g:

CONFIG +=link_pkgconfig
TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .
PKGCONFIG = gtk+-2.0
 
# Input
SOURCES += main.cpp

See the documentation http://doc.qt.io/qt-5/qmake-project-files.html#configuration-features.



How can I align the text and icons in an itemview?

You can align the text and icons in your itemview by subclassing the itemview and reimplementing viewOptions() http://doc.qt.io/qt-5/qabstractitemview.html#viewOptions to return the alignment you want for the QStyleOptionViewItem http://doc.qt.io/qt-5/latest/qstyleoptionviewitem.html.

The example below demonstrates how this can be done.

#include <QtGui>  
 
class ListWidget : public QListWidget 
{ 
public:
    ListWidget()     
    {         
        QListWidgetItem *item1 = new QListWidgetItem("one");         
        QListWidgetItem *item2 = new QListWidgetItem("two");         
        QListWidgetItem *item3 = new QListWidgetItem("three");         
        addItem(item1);         
        addItem(item2);
        addItem(item3);
    }           
 
    QStyleOptionViewItem viewOptions() const
    {         
        QStyleOptionViewItem item;         
        item.init(this);
        item.displayAlignment = Qt::AlignRight;         
        return item;
    } 
};  
 
int main(int argc, char** argv) 
{     
    QApplication app(argc, argv);     
    ListWidget listWidget;
    listWidget.show();
    return app.exec();
}

How can I change the margins of my QTextDocument?

In order to specify the margins used by the whole document you can follow these steps:

  1. Get the root frame that contains the document using QTextDocument::rootFrame() http://doc.qt.io/qt-5/qtextdocument.html#rootFrame
  2. Then get the QTextFrameFormat through QTextFrame::frameFormat() http://doc.qt.io/qt-5/qtextframe.html#frameFormat.
  3. Then call QTextFrameFormat::setMargin() http://doc.qt.io/qt-5/qtextframeformat.html#setMargin with the desired value.

In order to specify individual margins (independently) for each block of text, you can use the QTextBlockFormat http://doc.qt.io/qt-5/qtextblockformat.html#setTopMargin set margin functions.

The example below demonstrates how to set margins for the entire document and also how to set the margins for individual blocks.

#include <QtGui>  
 
int main(int argc, char** argv) 
{     
    QApplication app(argc, argv);     
    QTextEdit edit;     
    edit.setText("The QTextEdit widget is an advanced editor that supports "
                 "formatted rich text. ");
    edit.append("It can be used to display HTML and other rich document formats.");          
    QTextDocument * doc = edit.document();     
    QTextCursor cursor(doc);     
    cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);     
    //cursor.movePosition(QTextCursor::Start, QTextCursor::KeepAnchor);  
#if 1     
    QTextBlockFormat tbf = cursor.blockFormat();      
    tbf.setLeftMargin(100);     
    tbf.setTopMargin(100);
    cursor.setBlockFormat(tbf); 
#else        
    QTextFrame *tf = doc->rootFrame();
    QTextFrameFormat tff = tf->frameFormat();     
    tff.setMargin(50);
    tf->setFrameFormat(tff);  
#endif      
    edit.show();     
    return app.exec(); 
}

Is is possible to run Qt applications on Windows XP Embedded ?

This should work since the Windows API is the same for Windows XP and Windows XP Embedded and since they are binary compatible, but it is not supported or tested by us.


I use a shortcut for interacting with a widget in my QTest::keyClick() function and the test fails. What can be wrong?

The problem is likely to be that you have not called show() http://doc.qt.io/qt-5/latest/qwidget.html#show on your widget. If the widget is not visible, the shortcut does not actually behave correctly. You wouldn't typically have a shortcut that works for a non visible widget, so you should show your widget to get this test to pass.


How can I change the icon for the sort indicator and its position in a QHeaderView?

In order to change the icon and position for the sort indicator in a QHeaderView http://doc.qt.io/qt-5/qheaderview.html, you can subclass the style and reimplement drawPrimitive() http://doc.qt.io/qt-5/qstyle.html#drawPrimitive to draw the sort indicator using the icon and position you want.

#include <QtGui>  
 
class Style: public QWindowsStyle 
{ 
public:   
    Style () {}  
    void drawPrimitive(PrimitiveElement element, const QStyleOption *option, 
                       QPainter *painter, const QWidget *widget = 0) const   
    {   
        if (element == PE_IndicatorHeaderArrow )   {    
            const QStyleOptionHeader *headerOption = 
               qstyleoption_cast<const QStyleOptionHeader *>(option);    
            int x, y, width, height;    
            option->rect.getRect(&x, &y, &width, &height);
            QPixmap pixmap;    
 
            if (headerOption->sortIndicator == QStyleOptionHeader::SortUp)     
                pixmap.load("arrow_up.png");    
            else
                pixmap.load("arrow_down.png");    
 
            painter->save();
            painter->drawPixmap(x+width,y+height,pixmap);    
            painter->restore();   
        } else    
            QWindowsStyle::drawPrimitive(element, option, painter, widget);  
    } 
};
 
int main(int argc, char **argv)
{  
    QApplication app(argc, argv);  
    QTableWidget table(2,2);   
    QTableWidgetItem *item1 = new QTableWidgetItem("1");
    QTableWidgetItem *item2 = new QTableWidgetItem("2");  
    table.setItem(0,0, item1);  
    table.setItem(1,0, item2);    
    table.setSortingEnabled(true);
    app.setStyle(new Style());  
    table.show();  
    return app.exec();   
}

Alternatively, you can use a stylesheet to achieve this. See the documentation:

http://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qheaderview


When creating a library with Qt/Windows and using it in an application, then there is a link error regarding symbols which are in the library

When seeing errors like the following:

MyObj.obj : error LNK2019: unresolved external symbol  public: static
struct QMetaObject const MyObj::staticMetaObject"
(?staticMetaObject@MyObj@@2UQMetaObject@@B) referenced in function  class
MyObj * __cdecl qobject_cast<class MyObj *>(class  QObject *)"

it is probably a result of the linker not finding the symbols from the library. You need to make sure that the symbols in your library are properly exported when the library is created. Subsequently imported when you are linking against the library, so you should have something like the following in a header file in your library:

#if defined TEST
#define TEST_COMMON_DLLSPEC __declspec(dllexport)
#else
#define TEST_COMMON_DLLSPEC __declspec(dllimport) 
#endif


and use it in the classes that you wish to make available to the application like:


    class TEST_COMMON_DLLSPEC MyObj : public QObject { ... };

Then add to your library's .pro file the following line so it knows that the symbols need to be exported in this case:


    DEFINES += TEST

See the following wiki page http://wiki.qt.io/How_to_create_a_library_with_Qt_and_use_it_in_an_application for more information and a complete example.

How can I enable Edit and Continue in my Qt application?

Edit and Continue is not enabled by default for Qt projects since project files, created with qmake -tp vc contain the compiler switch */Zi*. To enable edit & continue, the right switch would be */ZI*.

To enable Edit & Continue in your .pro file, add the following to the .pro file:

QMAKE_CFLAGS_DEBUG      += -ZI
QMAKE_CXXFLAGS_DEBUG += -ZI

Alternatively, you can enable Edit & Continue for your project inside Visual Studio, as follows:

  • open the project settings
  • select C/C++ -> General"
  • set Debug Information Format to Program Database for Edit & Continue (/ZI)"


Is there a way to specify build dependencies for Visual Studio 2003 and 2005?

There are a couple of precautions you need to be aware of for the automatic dependency generation to work properly in MS Solution files. The attached example demonstrates how this can be done by following the steps below.

 The dependencies are generated automatically, if

1a) there is a Lib/DLL project with the target name (the .lib is used, not the .dll of course) being that of what is used on link line of an other project in your solution

1b) there is a Exe project with the target name being that of what is used in a custom build-step of an other project in your solution

2) you don't use paths in the TARGET variable (use DESTDIR/DLLDESTDIR for that), like TARGET=$(SOME_VARIABLE)/myLib, won't work

3) if you have a special location for your libs, you specify the -Lmy/library/path and LIBS += mylib, instead of just using LIBS += my/library/path/mylib

4) the leaf projects are created before you generate the solution file. (You can use the recursive flag for qmake to do this, like qmake -tp vc -r [yourproject.pro]"

See also:

http://lists.trolltech.com/qt-interest/2006-07/thread00238-0.html


Are there seperate versions for CDT 3.1 and CDT 4.0?

No, the provided Qt Eclipse Integration package works with both CDT versions.


How can I move the origin of a QGraphicsScene to the top left corner of the view?

By default, the scene rectangle will be aligned to the view's center. So when the view gets larger, the scene will stay in the center of it. You can change the alignment of the scene with the QGraphicsView::setAlignment() http://doc.qt.io/qt-5/qgraphicsview.html#alignment-prop function.


How can I make the focus go from one cell to the next when hitting Enter?

In order to make the focus go from one cell to the next in a table when hitting Enter, you can reimplement the delegate's eventFilter() http://doc.qt.io/qt-5/latest/qstyleditemdelegate.html#eventFilter and listen for QEvent::KeyPress http://doc.qt.io/qt-5/latest/qevent.html#Type-enum. Then when the key is Enter, you can simply emit commitData(editor) and closeEditor(editor,QAbstractItemDelegate::EditNextItem) and return.

See the documentation on commitData() http://doc.qt.io/qt-5/latest/qabstractitemview.html#commitData and closeEditor() http://doc.qt.io/qt-5/latest/qabstractitemview.html#closeEditor

The following example demonstrates how this can be done:

#include <QtGui>
class MyItemDelegate : public QStyledItemDelegate
{
  Q_OBJECT
public:
  MyItemDelegate(QObject *parent = 0) : QStyledItemDelegate(parent)
  {
    installEventFilter(this);
  }
  bool eventFilter ( QObject * editor, QEvent * event )
  {
    if (event->type() == QEvent::KeyPress)
    {
      QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
      if (keyEvent->key() == Qt::Key_Return) 
      {
        qDebug() << "Ate key press" << keyEvent->key();
        emit commitData((QWidget*)editor);
        closeEditor((QWidget*)editor, QAbstractItemDelegate::EditNextItem);
        return true;
      }
    }
    return QStyledItemDelegate::eventFilter(editor, event);
  }
};
class TableWidget : public QTableWidget
{
  Q_OBJECT
public:
  TableWidget()
  {
    setItemDelegate(new MyItemDelegate());
    setColumnCount(5);
    setRowCount(5);
 
  }
};
 
#include "main.moc"
 
int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  TableWidget box;
  box.show();
  return app.exec();    
}

How to avoid that space is replaced with %20 when writing .ini files?

The only way to avoid space being replaced by %20 in the .ini file is to change the Qt code to not escape it, however the reason it is escaped is because the space character is not permitted as a key name in an ini file, see:

http://doc.qt.io/qt-5/qsettings.html#setIniCodec

What you should do here is either post-process the file to replace the escaped characters back . The other option is to register your own format with registerFormat() http://doc.qt.io/qt-5/qsettings.html#registerFormat.




Why doesn't my service created with QtService start?

In order for a service to start it is necessary to copy over the Qt dlls that are being used to the same directory as your application.exe. This is necessary to do because a service is started with only system environment variables set. i.e. QTDIR/bin is usually not part of that environment, so the system is most likely not able to locate the Qt dlls.


How to allow only a single column to be editable in a QTreeWidget?

The flags for QTreeWidgetItems http://doc.qt.io/qt-5/latest/qtreewidgetitem.html are set for the entire item and all columns. For more flexibility, you may wish to use a QTreeView http://doc.qt.io/qt-5/latest/qtreeview.html and QStandardItemModel http://doc.qt.io/qt-5/latest/qstandarditemmodel.html, which lets you set the flags on individual items.

The documentation for QStandardItemModel contains a small example on how to create a tree model.


How do I make a combobox look similar to the one used in file dialogs?

The differences with the combobox used in a file dialog is that it shows a hierarchical view and although this is possible by padding items with space you run into problems when you have icons as well as text as the icons are not padded.

To achieve this functionality then you can set a QTreeView http://doc.qt.io/qt-5/latest/qtreeview.html on the QComboBox http://doc.qt.io/qt-5/latest/qcombobox.html and with a tweak of some of the settings you can get it to resemble the combobox used on a QFileDialog http://doc.qt.io/qt-5/latest/qfiledialog.html.

The following is an example of how this can be done:

#include <QtGui>
 
int main(int argc, char **argv)
{
    QApplication a(argc, argv);
    QComboBox cb;
    QTreeView *tv = new QTreeView;
    tv->header()->hide();
    QStandardItemModel *sim = new QStandardItemModel(1, 1);
    QStandardItem *si = new QStandardItem;
    QPixmap pix(16, 16);
    pix.fill(Qt::red);
    si->setText("C:\\");
    si->setIcon(pix);
    QStandardItem *childSi = new QStandardItem;
    childSi->setText("windows");
    pix.fill(Qt::blue);
    childSi->setIcon(pix);
    si->insertRow(0, childSi);
    sim->setItem(0, 0, si);
 
    cb.setModel(sim);
    cb.setModelColumn(0);
    tv->setRootIsDecorated(false);
    cb.setView(tv);
    cb.show();
    QTimer::singleShot(0, tv, SLOT(expandAll()));
    return a.exec();
}

NB: The call to QTimer::singleShot() is necessary as the expansion of the items needs to occur after the QComboBox and QTreeView are fully initalized after it gets shown.


Setting thread processor affinity in Linux

If you want to set CPU affinity per QThread http://doc.qt.io/qt-5/latest/qthread.html, Qt does not provide an API do this, and you will need to use native platform calls. Qt provides a native handle to the currently running thread via the static method QThread::currentThreadId() http://doc.qt.io/qt-5/qthread.html#currentThreadId.

In Linux you will want to take a look at pthread_setaffinity_np() (in /usr/include/pthread.h) which lets you set the affinity of a thread. The id returned by QThread::currentThreadId() is the same as pthread_self(), so to change the affinity of the current thread, you could do something like this:

cpu_set_t cpuset;

CPU_ZERO(&cpuset);
CPU_SET(cpuNumber, &cpuset);

...

pthread_setaffinity((pthread_t) QThread::currentThreadId(), &cpuset);

You could just use pthread_self() as well, avoiding the cast.


Use of setCellWidget (in QTableWidget) and signal connections

The widgets set on the cells have nothing to do with the contents of the table, so you won't get signals from the table in such a case. If you have a row or column of widgets potentially emitting signals, and you want one slot to be notified of the row/column index of the widget that was triggered, then QSignalMapper http://doc.qt.io/qt-5/qsignalmapper.html#map could be the way to go.

The following example illustrates how this can be done:

main.cpp

#include <QtGui>
 
class CustomWidget : public QWidget{
    Q_OBJECT
 
public:
    CustomWidget(QWidget *parent = 0 , Qt::WindowFlags f = 0){
        table = new QTableWidget(7,4,this);
        signalMapper = new QSignalMapper(this);
        statusBar = new QStatusBar(this);
 
        for (int i = 0; i< table->rowCount(); i++){
            QComboBox *cb = new QComboBox();
            cb->addItems((QStringList() << "Item 1" << "Item 2" << "Item 3"));
            table->setCellWidget(i,2,cb);
            connect(cb, SIGNAL(currentIndexChanged(int)), signalMapper, SLOT(map()));
            signalMapper->setMapping(cb, i);
        }
        connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(demoSlot(int)));
        setLayout(new QVBoxLayout);
        layout()->addWidget(table);
        layout()->addWidget(statusBar);
        resize(400,300);
        show();
    }
 
 
public slots:
    void demoSlot(int row){
        QComboBox *cb = static_cast<QComboBox *>(table->cellWidget(row,2));
        statusBar->showMessage(QString("Combobox changed at row %1, "\
                                       "new value: %2").arg(row+1).arg(cb->currentText()), 5000);
    }
 
private:
    QTableWidget *table;
    QSignalMapper *signalMapper;
    QStatusBar *statusBar;
};
 
#include "main.moc"
 
int main( int argc, char** argv ){
 
   QApplication app( argc, argv );
        CustomWidget w;
        w.show();
   return app.exec();
}


When doing Qt | Open Solution from .pro file in Visual Studio 2005 I get an error saying the sln file is from a previous version of Visual Studio and must be converted, what can I do?

This problem can occur if you have both 2003 and 2005 installed, then these versions will conflict. What you need to do is either:

  1. Open the sln file in Visual Studio 2005 and you will get a conversion dialog. Answer yes in this dialog and the sln file will be converted to the 2005 format instead of 2003.
  2. Use the command prompt that can be found under *Start menu | Visual Studio 2005 | Command prompt*. Type *devenv /usenv* in this command prompt and this will ensure that the correct environment variables are set and that you should be able to use the Open Solution from .pro file option inside Visual Studio.


When building with Visual C++, it uses a different copy of a specified file that has the same name. How do I fix this?

This is a problem with nmake not respecting the path for the file when building in batch mode, it will find the first copy of the file in the paths and assume that is the right one. You can work around this problem by doing:

CONFIG += no_batch

in your pro file.


I am having problems displaying overlays on Linux with my NVIDIA card. The same code works on windows.

The NVIDIA driver only offers RGBA overlays. The default setting in QGLFormat is to use an index-based overlays. You can switch to RGBA overlays using this code:

     QGLFormat f = QGLFormat::defaultOverlayFormat();
     f.setRgba(true);
     QGLFormat::setDefaultOverlayFormat(f);

How to add to the beginning of a QDomDocument?="<?xml version

'1.0'?> is added by creating a processing instruction as the

first child of the document:

 
    QDomDocument doc;
    doc.appendChild(doc.createProcessingInstruction(xml version =,'1.0'));
    doc.appendChild(doc.createElement("hi"));


How can I do drag and drop in a widget?

Drag and drop support in Qt is centered around the QDrag http://doc.qt.io/qt-5/qdrag.html class that handles most of the details of a drag and drop operation.

In addition to creating a QDrag object, you need to reimplement dragMoveEvent() http://doc.qt.io/qt-5/qwidget.html#dragMoveEvent to accept the event and dropEvent() http://doc.qt.io/qt-5/qwidget.html#dropEvent to handle the data dropped on the widget. Finally dragEnterEvent() http://doc.qt.io/qt-5/latest/qwidget.html#dragEnterEvent needs to be reimplemented to accept the event.

You also need to call

setAcceptDrops(true)

on the widgets that should be able to accept a drop.

For more information, read the general documentation http://doc.qt.io/qt-5/dnd.html on drag and drop:

The example below illustrates how this can be done.

#include <QtGui>
 
class MyDialog : public QWidget
{
    Q_OBJECT
public:
    MyDialog(QWidget *parent = 0);
public slots:
    void makeDrag();
protected:
    void dropEvent(QDropEvent *de);
    void dragMoveEvent(QDragMoveEvent *de);
    void dragEnterEvent(QDragEnterEvent *event);
};
 
class MyGroupBox : public QGroupBox
{
public:
    MyGroupBox(QWidget *parent = 0) : QGroupBox(GroupBox, parent) {};
protected:
    void dropEvent(QDropEvent *de);
    void dragMoveEvent(QDragMoveEvent *de);
    void dragEnterEvent(QDragEnterEvent *event);
};
 
 
MyDialog::MyDialog(QWidget *parent) : QWidget(parent)
{
    QHBoxLayout *layout = new QHBoxLayout(this);
    QPushButton *pushButton = new QPushButton(Click Me, this);
    layout->addWidget(pushButton);
    connect(pushButton, SIGNAL(pressed()), this, SLOT(makeDrag()));
    MyGroupBox *box = new MyGroupBox(this);
    layout->addWidget(box);
    // Allow media to be dropped on the widget
    setAcceptDrops(true);
    box->setAcceptDrops(true);
}
 
void MyDialog::makeDrag()
{
    QDrag *dr = new QDrag(this);
    // The data to be transferred by the drag and drop operation is contained in a QMimeData object
    QMimeData *data = new QMimeData;
    data->setText(This is a test);
    // Assign ownership of the QMimeData object to the QDrag object.
    dr->setMimeData(data);
    // Start the drag and drop operation
    dr->start();
}
 
void MyDialog::dragMoveEvent(QDragMoveEvent *de)
{
    // The event needs to be accepted here
    de->accept();
}
 
void MyDialog::dragEnterEvent(QDragEnterEvent *event)
{
    // Set the drop action to be the proposed action.
    event->acceptProposedAction();
}
 
void MyDialog::dropEvent(QDropEvent *de)
{
    // Unpack dropped data and handle it the way you want
    qDebug(Contents: %s, de->mimeData()->text().toLatin1().data());
}
 
void MyGroupBox::dropEvent(QDropEvent *de)
{
    // Unpack dropped data and handle it the way you want
    qDebug(Contents: %s, de->mimeData()->text().toLatin1().data());
}
 
void MyGroupBox::dragMoveEvent(QDragMoveEvent *de)
{
    // The event needs to be accepted here
    de->accept();
}
 
void MyGroupBox::dragEnterEvent(QDragEnterEvent *event)
{
    // Set the drop action to be the proposed action.
    event->acceptProposedAction();
}
 
#include main.moc"
 
int main(int argc, char **argv)
{
    QApplication a(argc, argv);
    MyDialog d;
    d.show();
    return a.exec();
}

How can I tell qmake to have more than one target in a directory?

You can add your own targets in your .pro file using the variable *QMAKE_EXTRA_TARGETS*

For more information see:

http://doc.qt.io/qt-5/qmake-environment-reference.html#customizing-makefile-output

This will allow you to have several executables in the same directory.


How can I get hold of all of the visible items in my QTreeWidget?

In order to get a list of the visible items in a QTreeWidget http://doc.qt.io/qt-5/latest/qtreewidget.html, then you can use itemAt(0,0) to get the first item, then use itemBelow() http://doc.qt.io/qt-5/qtreewidget.html#itemBelow to get the next and then do,

if (viewport()->rect().contains(visualItemRect(itemBelow(myItem))

to determine if it's actually on the viewport or not. See the documentation:

http://doc.qt.io/qt-5/qtreewidget.html#itemAt http://doc.qt.io/qt-5/qtreewidget.html#visualItemRect

The following example demonstrates how this can be done:

#include <QtGui>
 
QList <QTreeWidgetItem*>myList;
class TreeWidget : public QTreeWidget
{
  Q_OBJECT
public:
  TreeWidget()
  {
    QStringList list;
    list << "An item";
    QTreeWidgetItem *item1 = new QTreeWidgetItem(list);
 
    for (int i = 0; i < 100; i++) {
      item1->addChild(new QTreeWidgetItem(item1, list));
    }
 
    QTreeWidgetItem *item2 = new QTreeWidgetItem(list);
    QTreeWidgetItem *item3 = new QTreeWidgetItem(list);
    QTreeWidgetItem *item4 = new QTreeWidgetItem(list);
 
    addTopLevelItem(item1);
    addTopLevelItem(item2);
    addTopLevelItem(item3);
    addTopLevelItem(item4);
    item1->setExpanded(true);
 
  }
  public slots:
    void test1()
    {
      QTreeWidgetItem *myItem = itemAt(0,0);
      if (myItem) {
        qDebug() << "I am visible";
        myList << myItem;
      }
      while (itemBelow(myItem)) {
        if (viewport()->rect().contains(visualItemRect(itemBelow(myItem)))) {
          myItem = itemBelow(myItem);
          myList << myItem;
          qDebug() << "I am visible";
        }else{
          qDebug() << "I am visible";
          myList << myItem;
          break;
        }}
      qDebug() << myList.count() << " visible items" ;}
};
 
#include "main.moc"
 
int main(int argc, char** argv)
{
  QApplication app(argc, argv);
  TreeWidget window;
  window.show();
  window.test1();
  return app.exec();
 
}

Why is the debug version of my application so slow?

This is due to the fact that Microsoft Visual C++ .NET's debug version of the runtime libraries are slow, and by default Qt will link against the debug version of the runtime library if you configure Qt in debug mode. There is a workaround for this, simply do the following:

  1. Edit your qt\mkspecs\win32-msvc.net[2003/2005/2008]\qmake.conf file
  2. Where it states **-MDd** change it to be **-MD**
  3. Go into your qt directory
  4. nmake distclean
  5. Do configure -redo
  6. nmake

Then all that is left is to regenerate the Makefile for your application and rebuild it.


Why isn't the parent's font propagated to QAbstractItemView subclasses on Windows?

The reason the parent's font is not propagated to subclasses of QAbstractItemView http://doc.qt.io/qt-5/latest/qabstractitemview.html is that it has its own font set in qapplication_win.cpp. This is to ensure that the itemviews have a font that matches what you would get in a native itemview on Windows.

To have the font propagated you need to set the font for the relevant class to an empty font in your QApplication http://doc.qt.io/qt-5/latest/qapplication.html, e.g.:

QApplication::setFont(QFont(), "QAbstractItemView");

Another option is to set a stylesheet http://doc.qt.io/qt-5/latest/stylesheet.html:

app.setStyleSheet("*{font ...}");


How does Qt::WA_PaintOnScreen relate to the backing store, widget composition and double buffering?

The behavior of the Qt::WA_PaintOnScreen http://doc.qt.io/qt-5/qt.html#WidgetAttribute-enum attribute is dependent on the platform it is used on.

On X11, setting this attribute will disable all double buffering and widget composition and let QPainter http://doc.qt.io/qt-5/qpainter.html draw directly onto the screen.

On Windows, this attribute is not supported by itself. It can only be used in combination with reimplementing QWidget::paintEngine() http://doc.qt.io/qt-5/qwidget.html#paintEngine to use custom paint engines. Reimplementing paintEngine() to return a null engine will give the user the option of drawing directly to the widget's HDC. Setting this flag will disable widget composition, but a double buffer will still be used for the widget.

On Mac OS X, double buffering and widget composition is done entirely by the windowing system, and setting this flag has no effect.


Does Qt Assistant support the MNG format?

Qt Assistant http://doc.qt.io/qt-5/latest/assistant-manual.html does not support the MNG format (the animated PNG format).


I am getting linking errors when trying to link against msvcrtd.lib. And when linking against libcmt.lib the application crashes. What can I do ?

Qt is pre-built against the shared C runtime -MD(d), as this is the only C runtime that can be used safely in an environment where heap-allocated objects are passed around accross DLL boundaries (which is what you do all the time when creating QObjects or QWidgets - you create them in your heap, and usually pass them on as children of other objects so that Qt can take care of deleting them).


If you link Qt against the static libcmt.lib or if you link your Qt applications against libraries that that are built against the static C runtime library then you will get a mismatch of runtime libraries. This means that there are two heaps in use and as a result if objects get passed from one heap to another (i.e. from Qt to the application and vice versa) then memory corruption will occur. You can usually catch this at build time, if you see a link warning about default libraries then this is usually indicative of this problem. The only way to resolve it is to ensure that everything is built in the same mode.

When linking against msvcrtd.lib instead of libcmt.lib, then you might get linking errors reporting two unresolved symbols, __pctype, and ___mb_cur_max. msvcrtd.lib does contain those two symbols, however they are not automatically located. It is necessary to create a dummy source file that just references those two symbols:

extern C { 
    int __mb_cur_max; 
    unsigned short* _pctype;
    int errno; 
}


Why do I get hundreds of warnings when the compiler warning level is set to level 4 for .NET 2003?

We do not support building with warning level 4. The warnings generated at this level are often not valid, this is why we build at warning level 3.


Is building Qt on a 64bit AMD platform with Windows supported?

You can build the source package on 64bit AMD platforms provided you use the 64 bit command line shell that comes with Visual Studio. The Qt binary package is prebuilt in 32 bit, so it is necessary to use the source package. Note that the mkspec for Visual Studio .NET 2005 uses win32, but this is only because Visual Studio .NET 2005 works on 32bit platforms as well. The following suggestion http://bugreports.qt.io/browse/QTBUG-452 is listed in the Bug Tracker for adding a separate configuration for Win64.



When 2 views share the same model, how can the views get different values for some of the Qt::ItemDataRole roles?

The model does not have any information about the views, so your item delegate will have to handle this. If you want one of your views to have icons and not the other one, then you can reimplement QItemDelegate::drawDecoration() http://doc.qt.io/qt-5/qitemdelegate.html#drawDecoration and set the delegate on that view, e.g:

#include <QtGui>
 
class ItemDelegate : public QItemDelegate
{
public:
    ItemDelegate() : QItemDelegate()
    {
    }
 
    void drawDecoration(QPainter *painter, const QStyleOptionViewItem &option,
                        const QRect &rect, const QPixmap &pixmap) const
    {
        QPixmap pix(22, 22);
        pix.fill(Qt::red);
        QItemDelegate::drawDecoration(painter, option, option.rect, pix);
    }
};
 
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QWidget widget;
    QHBoxLayout *layout = new QHBoxLayout(&widget);
    QTableView *tableView = new QTableView(&widget);
    tableView->setItemDelegate(new ItemDelegate());
    QTableView *secondtableView = new QTableView(&widget);
    QStandardItemModel *model = new QStandardItemModel;
    model->insertRows(0, 4);
    model->insertColumns(0, 4);
    for (int row = 0; row < 4; row++) {
        for (int col = 0; col < 4; col++) {
            QModelIndex index = model->index(row, col);
            model->setData(index, QVariant((row+1) * (col+1)).toString());
        }
    }
    secondtableView->setModel(model);
    tableView->setModel(model);
 
    layout->addWidget(tableView);
    layout->addWidget(secondtableView);
 
    widget.show();
    return app.exec();
}

Alternatively, you can reimplement QItemDelegate::paint() http://doc.qt.io/qt-5/qitemdelegate.html#paint and draw the pixmap and the other details there.



How can I make both the item picture and the item text transparent in the drag icon so that user can see what is under the drag icon?

Whether or not transparent drag icons are supported is platform dependent. For instance Windows 2000 does not support this. So the simplest way to achieve this is to display what you want to drag in a toplevel QLabel http://doc.qt.io/qt-5/latest/qlabel.htmland give this label a window opacity http://doc.qt.io/qt-5/latest/qwidget.html#windowOpacity-prop


I can still insert numbers outside the range specified with a QDoubleValidator on a QLineEdit, is this a bug?

The validator will return an Intermediate http://doc.qt.io/qt-5/qvalidator.html#State-enum value for text that is a double but outside the range. The line edit will accept the intermediate values since it means that only a bit of editing is required to fix the value. This is because you might want to do something like pasting a number with 10 decimals with a validator that only allows 2 and then remove some of them.

The example below reimplements validate() http://doc.qt.io/qt-5/qvalidator.html#validate to make the validator more strict:

#include <qapplication.h>
#include <qmainwindow.h>
#include <qvalidator.h>
#include <qlineedit.h>
 
class MyDoubleValidator : public QDoubleValidator
{
public:
    MyDoubleValidator( double bottom, double top, int decimals, QObject*
        parent = 0, const char* name = 0 )
        : QDoubleValidator( bottom, top, decimals, parent, name )
    {}
 
    QValidator::State validate ( QString & input, int &pos ) const
    {
        if ( input.isEmpty() || input == . )
            return Intermediate;
        if ( QDoubleValidator::validate( input, pos ) != Acceptable ) {
            return Invalid;
        }
        return Acceptable;
    }
};
 
class Widget : public QMainWindow
{
    Q_OBJECT
public:
    Widget( QWidget* parent = 0, const char* name = 0 )
        : QMainWindow( parent, name )
    {
        QLineEdit* edit = new QLineEdit( this );
        setCentralWidget( edit );
        edit->setValidator( new MyDoubleValidator( 0.0, 1.0, 3, edit ) );
    }
};
 
#include main.moc"
 
int main( int argc, char **argv )
{
    QApplication a( argc, argv );
    Widget w;
    w.show();
    return a.exec();
}

How can I draw one of my menu items, e.g Help, to the right in the menubar ?

You can call insertSeparator() http://doc.qt.io/qt-5/qmenu.html#insertSeparator in order to insert a separator before the Help action. Whether or not this separator is drawn, is style dependent however. It will not be drawn in the Windows(XP) Style. So you can either call

menuBar()->setStyle(new QMotifStyle())

or subclass the style and reimplement the stylehint() http://doc.qt.io/qt-5/qstyle.html#styleHint to return the SH_DrawMenuBarSeparator http://doc.qt.io/qt-5/latest/qstyle.html#StyleHint-enum hint.

The following example demonstrates how this can be done:

    #include <QtGui>
 
    class Style : public QWindowsStyle
    {
    public:
      Style()
      {}
 
    int styleHint(StyleHint hint, const QStyleOption *option = 0, const QWidget *widget = 0, QStyleHintReturn *returnData = 0) const
      {
      if (hint == QStyle::SH_DrawMenuBarSeparator)
      return 1;
       return QWindowsStyle::styleHint(hint, option, widget, returnData);
      }
    };
 
    class MainWindow : public QMainWindow
    {
    public:
      MainWindow()
      {
      QMenu *menu = new QMenu("File", this);
      menu->addAction("An action");
      QMenu *menu2 = new QMenu("Help", this);
      menu2->addAction("Another action");
      menuBar()->addMenu(menu);
      menuBar()->addMenu(menu2);
      //menuBar()->setStyle(new QMotifStyle()); //As an alternative to styleHint(), set the Motif style
 
      menuBar()->setStyle(new Style());
      menuBar()->insertSeparator(menu2->menuAction());
      }
    };
 
    int main(int argc, char **argv)
    {
      QApplication app(argc, argv);
      MainWindow box;
      box.show();
      return app.exec();
    }

How can I turn off the debug and release Makefile generation for my application?

Simply add the following line to your pro file:

 CONFIG -= debug_and_release


When setting a pixmap with an alpha on a widget, how can I remove the widget's gray edges that shine through?

In order to remove the non-transparent edges from the widget, you can set a heuristic mask on the pixmap. This will cause the outer most color to be removed where it is used in the pixmap. Then you can set the QBitmap http://doc.qt.io/qt-5/latest/qbitmap.html which is returned from the call to createHeuristicMask() http://doc.qt.io/qt-5/qpixmap.html#createHeuristicMask as a mask on your widget. This will cause only the pixels of the widget for which bitmap has a corresponding 1 bit to be visible. Now you can set your pixmap on the widget, and only the pixels that correspond to where the mask has a bit set will be visible.

See the following example for a demonstration:

    #include <QtGui>
 
    int main(int argc, char **argv)
    {
        QApplication app(argc, argv);
        QPixmap pixmap("pix_with_alpha");
        QBitmap bm(pixmap.createHeuristicMask());
        QSplashScreen splash(0);
        splash.setMask(bm);
        splash.setPixmap(pixmap);
        splash.show();
        return app.exec();
    }

Is it possible to have no icons in the menu when using actions but use the same actions on a toolbar and have an icon there?

On the Mac you can call

qt_mac_set_Menubar_icons(false)

this will prevent the icons from showing up in the menu. See the documentation http://doc.qt.io/qt-5/exportedfunctions.html#void-qt-mac-set-menubar-icons-bool-enable.

Alternatively, you can iterate over the toolbar's toolbutton children and set an icon http://doc.qt.io/qt-5/qabstractbutton.html#icon-prop on them.

See the following example for a demonstration:

#include <QtGui>  
 
int main(int argc, char **argv)
{     
    QApplication app(argc, argv);              
    QPixmap pix(15,15);
    pix.fill(Qt::red);              
    QMainWindow box;                  
    QAction *action = new QAction("First action", &box);         
    QAction *action2 = new QAction("Second action", &box);                  
    QToolBar *toolBar = new QToolBar(&box);
    toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
    toolBar->addAction(action);         
    toolBar->addAction(action2);
    QList<QToolButton*> toolButtons = qFindChildren<QToolButton*>(toolBar);
    for (int i = 0; i < toolButtons.size(); i++) {                 
        QToolButton *button = (QToolButton*)toolButtons.at(i);
        button->setIcon(pix);         
    }                           
    QMenu *menu = new QMenu("File", &box);         
    menu->addAction(action);
    menu->addAction(action2);         
    box.menuBar()->addMenu(menu);
    box.addToolBar(toolBar);         
    box.show();         
    return app.exec();
}

Can you suggest a tool which we can use to track down memory leaks in Qt?

Qt doesn't limit your use of memory tools, so the best thing to do is to try out the different tools available to see what works best for you.

Internally, we use Purify on Windows and on Linux we use Valgrind.


How can I check which tab is the current one in a tabbed QDockWidget?

You need to find the QTabBar http://doc.qt.io/qt-5/qtabbar.html that exists for the tabbed dockwidgets and then simply call tabBar->currentIndex() http://doc.qt.io/qt-5/qtabbar.html#currentIndex-prop on it to find the current index and connect a slot to the tabbar's currentChanged() http://doc.qt.io/qt-5/qtabbar.html#currentChanged slot. The example below shows how you can do this.

#include <QtGui>
class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget *parent = 0)
        : QMainWindow(parent)
    {
        QWidget *w = new QWidget(this);
        setCentralWidget(w);
        QVBoxLayout *layout = new QVBoxLayout(w);
 
        QDockWidget *d0 = new QDockWidget("Dock 0");
        d0->setFeatures(QDockWidget::NoDockWidgetFeatures);
        d0->setWidget(new QTextEdit);
        QDockWidget *d1 = new QDockWidget("Dock 1");
        d1->setFeatures(QDockWidget::NoDockWidgetFeatures);
        d1->setWidget(new QTextEdit);
        QDockWidget *d2 = new QDockWidget("Dock 2");
        d2->setFeatures(QDockWidget::NoDockWidgetFeatures);
        d2->setWidget(new QTextEdit);
 
        addDockWidget(Qt::LeftDockWidgetArea, d0);
        addDockWidget(Qt::LeftDockWidgetArea, d1);
        addDockWidget(Qt::LeftDockWidgetArea, d2);
 
        tabifyDockWidget(d0, d1);
        tabifyDockWidget(d1, d2);
 
        // get the QTabBar
        QList<QTabBar *> tabList = findChildren<QTabBar *>();
        if(!tabList.isEmpty()){
            QTabBar *tabBar = tabList.at(0);
      tabBar->setCurrentIndex(1);
            QString currentTab = tabBar->tabText(tabBar->currentIndex());
      qDebug() << currentTab;
      connect(tabBar, SIGNAL(currentChanged(int)), this, SLOT(testSlot(int)));
        }
    }
  public slots:
    void testSlot(int index)
    {
      qDebug() << "current tab is " << index; 
    }
};
 
#include "main.moc"
 
int main(int argc, char **argv)
{
    QApplication a(argc, argv);
    MainWindow mw;
    mw.show();
    return a.exec();
}

How can we remove properties from custom widgets in Designer?

You can remove properties from custom widgets in Designer using the QtDesignerPropertySheetExtension http://doc.qt.io/qt-5/qdesignerpropertysheetextension.html. This class allows you to manipulate a widget's properties which are displayed in Qt Designer's property editor.

You can setVisible(false) to hide the properties you want in Designer. See the documentation on setVisible() http://doc.qt.io/qt-5/qdesignerpropertysheetextension.html#setVisible.



How can I open my .html file in a browser?

You can use QDesktopServices http://doc.qt.io/qt-5/qdesktopservices.html to open a URL with the appropriate application for the system. So if you call

    QDesktopServices::openUrl("http://qt.io/");

then a web browser as set by the system will be invoked to display the page. The actual web browser used depends on the system settings, so this could be Firefox, Internet Explorer, Opera or Safari etc.

If you need the page to be opened in e.g Firefox only, you can use QProcess http://doc.qt.io/qt-5/qprocess.html to start the browser and provide the appropriate arguments to Firefox.



How can I build executables/libraries in both release and debug mode on Windows?

Qt is built in both debug and release mode by default on Windows. When it comes to building your applications/libraries, you can specify

CONFIG += debug_and_release

in your .pro file (this is already on by default on Windows).

If you want only one configuration to be generated, then whatever is last on the CONFIG line with respect to debug and release will be the one that qmake generates. If you want it to build both configurations of your application/library, then you need to add:

CONFIG += build_all

to your pro file and then whenever you do nmake, both the debug and release versions will be built.


Who provides training for Qt?

A number of companies provide Qt training, in Asia, Europe and the US. See our training page http://www.qt.io/events/



Qt seems to ignore the key sequence Ctrl++, is this a valid key sequence that Qt should recognize?

This is due to the way the Qt accelerator system works. The SHIFT key transforms the key into another character, and since Qt's system is really character based, not key based, that sometimes becomes a problem. If the key sequence is changed to SHIFT+CTRL+= it will work on an EN keyboard-layout.

You can use the workaround in the example below to make the Ctrl++ accelerator work for English keyboard layouts as well. Note that this may not work for other keyboard layouts, but if you know which countries you are likely to target then you can add the appropriate shortcuts to solve this problem.

Note that only the use of standard shortcuts guarantees that the user will be able to use the shortcuts that the developer intended, a part from that it is recommended to use e.g the first character in a string in the shortcut see:

http://doc.trolltech.com/qkeysequence.html#keyboard-layout-issues

See the following example for a demonstration:

#include <QtGui> 
 
class MainWindow : public QMainWindow 
{
  Q_OBJECT
public:
  MainWindow::MainWindow() : QMainWindow() 
  { 
    QAction* action = new QAction("Test", this); 
    QMenu *menu = menuBar()->addMenu("File"); 
    menu->addAction(action);
    connect( action, SIGNAL(triggered()), this, SLOT (giveOutput()));
    action->setShortcut(Qt::SHIFT+Qt::CTRL+Qt::Key_Equal);
    action->setShortcut(Qt::CTRL+Qt::Key_Plus); 
  } 
 
  public slots: 
    void giveOutput() {
    qDebug("I was called"); }
};
 
#include "main.moc" 
 
int main(int argc, char **argv) 
{ 
  QApplication app(argc, argv); 
  MainWindow box; 
  box.show(); 
  return app.exec();
}

How can I draw a question mark on an existing pixmap?

You open a painter on the pixmap and depending on how your question mark is represented, draw either the text string ?, or a polygon or a painter path describing the shape of a question mark.


How can I run a Qt application on a Unix machine that doesn't have X11 installed?

Qt is divided into several libraries. QtCore http://doc.qt.io/qt-5/latest/qtcore.html, QtSql http://doc.qt.io/qt-5/latest/qtsql.html, QtNetwork http://doc.qt.io/qt-5/latest/qtnetwork.html and QtXml http://doc.qt.io/qt-5/latest/qtxml.html don't link against X11 so you can use classes contained in this library and run your application on a machine that doesn't have X11 installed.


Is there a way to set the size of the icon for the items in my item view?

You can call setIconSize() http://doc.qt.io/qt-5/qabstractitemview.html#iconSize-prop on the view, this will readjust the icon sizes for the items to whatever you set it to.

Note that QIcon only scales down and not up, therefore the original pixmap should be as large as the max size you want to scale up to.

#include <QtGui>  
 
int main(int argc, char **argv)
{         
    QApplication app(argc, argv);   
    QTableWidget box;
    box.horizontalHeader()->setStretchLastSection(true);    
    QPixmap pix(50,50);
    pix.fill(Qt::red);      
    QIcon icon(pix);        
    box.setIconSize(QSize(25,25));
    QTableWidgetItem *itemOne = new QTableWidgetItem("one");
    QTableWidgetItem *itemTwo = new QTableWidgetItem("two");
    QTableWidgetItem *itemThree = new QTableWidgetItem("three");
    itemOne->setIcon(icon);         
    box.setRowCount(5);     
    box.setColumnCount(5);
    box.setItem(0,0,itemOne);       
    box.setItem(1,0,itemTwo);
    box.setItem(2,0,itemThree);     
    box.show();     
    return app.exec();
}

When a signal is emitted, will all of the slots attached to it be executed before the emit returns? Or are the slots just scheduled to be executed whenever convenient?

Connections can be direct or queued. For direct connections, which is the default when connecting objects in the same thread, all of the slots will be executed before the emit returns. Slots connected to signals through a queued connection will be executed when control returns to the event loop.

The order of execution of the slots is undefined.


I have a complex control where I never want to draw a certain subcontrol, how can I achieve this in Qt 4?

In order to remove a subcontrol you need to subclass the style and reimplement drawComplexControl() http://doc.qt.io/qt-5/latest/qstyle.html#drawComplexControl and make a copy of the style option and remove that subcontrol from the styleoption.

Here is an example where the frame is removed from a QGroupBox http://doc.qt.io/qt-5/latest/qgroupbox.html

#include <QtGui>
 
class Style : public QWindowsStyle
{
  Q_OBJECT
public:
  Style() {}
  void drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, QPainter *painter, const QWidget *widget = 0 ) const {
    if (const QStyleOptionGroupBox *group = qstyleoption_cast<const QStyleOptionGroupBox*>(option)) {
      QStyleOptionGroupBox newGroupBox(*group);
      newGroupBox.subControls &= ~SC_GroupBoxFrame;
      QWindowsStyle::drawComplexControl(control, &newGroupBox, painter, widget);
    } else {
      QWindowsStyle::drawComplexControl(control, option, painter, widget);
    }}};
 
 
#include "main.moc"
 
int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  QWidget widget;
  QVBoxLayout *layout = new QVBoxLayout(&widget);
  QGroupBox *box = new QGroupBox(&widget);
  box->setStyle(new Style());
  box->setTitle("box");
  layout->addWidget(box);
  widget.show();
  return app.exec();
}

What does it mean if the build fails with fatal error U1054

If installation of Qt/Windows fails with a message like this:

fatal error U1054: cannot create inline file 'C:\Documents and Settings\user\Local Settings\Temp nz00868'

then the Windows system ran out of names for temporary files, or tried to generate a temporary file that already exists. Delete your temporary files and restart your Qt installation to work around the problem. You might have to close all your other application to be able to do so.


How can I transfer shortcuts that are not available in the child window to the parent window?

You can create actions and set a shortcut to them and then add the actions to both the parent and the child as illustrated in the example below:

#include <QtGui>
 
class Parent : public QWidget
{
  Q_OBJECT
public:
  Parent()
  {
    dialog = new QDialog(this);
    dialog->setWindowFlags(Qt::Window);
    dialog->show();
    dialog->setWindowTitle("Dialog");
    QAction *a = new QAction(this);
    a->setShortcut(QKeySequence("Ctrl+O"));
    addAction(a);
    connect(a, SIGNAL(activated()), this, SLOT(close()));
    dialog->addAction(a);
  }
 
private:
QDialog *dialog;
};
#include "main.moc"
int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  Parent box;
  box.show();
  return app.exec();
}

How can I stack the dockwidgets vertically in the top dock area?

We provide no API for stacking the widgets in the top dock area vertically, but you can achieve this however by performing a hack. Note that this is not supported and might not work in future versions of Qt as the internal API might change.

In the example below we subclass the private class QDockWidgetLayout and go over the main window's layout's children and cast them to our subclass and make sure to set the orientation to be vertical. Finally, we invalidate the layout to make sure it gets updated.

#include <QtGui> 
 
class MyDL :public QDockWidgetLayout 
{
public: MyDL(Qt::DockWidgetArea a, Qt::Orientation o) : QDockWidgetLayout(a, o) 
    {} 
};
 
int main(int argc, char **argv)
{
  QApplication app(argc, argv); 
  QMainWindow window;
  QDockWidget *dock1 = new QDockWidget(&window);
  QDockWidget *dock2 = new QDockWidget(&window); 
  QDockWidget *dock3 = new QDockWidget(&window);
  window.addDockWidget(Qt::TopDockWidgetArea, dock2);
  window.addDockWidget(Qt::TopDockWidgetArea, dock3);
  window.addDockWidget(Qt::TopDockWidgetArea, dock1); 
  window.show();
  QList<QLayout*> customLayout = qFindChildren<QLayout*>(window.layout());
  for (int i = 0; i < customLayout.size(); i++)
  { 
    MyDL *dl = (MyDL *)customLayout.at(i);
    dl->QDockWidgetLayout::orientation = Qt::Vertical;
    dl->invalidate();
  } 
  return app.exec();
}

How can I create transparent labels and buttons where the window's background pixmap shines through the label?

The label will be transparent by default, so the background pixmap of the parent will shine through the label. For the buttons you need to fill the QPalette::Button http://doc.qt.io/qt-5/latest/qpalette.html#ColorRole-enum color role to have no brush. Note that changing the palette will not work for all styles, it will for example not work for the XP and MacStyle which are pixmap based. For these styles you will have to draw this yourself in the paintEvent() http://doc.qt.io/qt-5/latest/qlabel.html#paintEvent or set a style that supports this on the button.

See the following example:

#include <QtGui>
 
int main(int argc, char **argv) 
{
  QApplication app(argc, argv);
  QPixmap pixmap(200, 200);
  {
    QPainter p(&pixmap);
    p.fillRect(0, 0, 200, 200, QRadialGradient(100, 100, 100, 150, 150));
  }
  QWidget parent;
  QPalette ppal = parent.palette();
  ppal.setBrush(parent.backgroundRole(), pixmap);
  parent.setPalette(ppal);
 
  QWidget *wid = new QWidget(&parent);
  QLabel *label = new QLabel("Testing 1, 2, 3, 4, 5, 6, 7, 8, ....", wid);
  QPushButton *button = new QPushButton(wid);
  button->setText("Button");
  button->setAutoFillBackground(false);
  QPalette pal = button->palette();
  pal.setBrush(QPalette::Button, Qt::NoBrush);
  button->setPalette(pal);
 
  QVBoxLayout *layout = new QVBoxLayout(wid);
  layout->addWidget(label);
  layout->addWidget(button);
  label->setFont(QFont("Arial", 30));
 
  parent.show();
  parent.resize(300, 200);
  int ret = app.exec();
  return ret;
}

My Designer plugin isn't loaded in Designer on Windows, even though I get the complied dll and lib. What's going on?

You need to make sure your plugin has the same configuration as the Qt library and see if it shows up in Qt Designer http://doc.qt.io/qt-5/latest/designer-manual.html then. When Qt is configured to build in both debug and release modes which is the default on Windows, then Qt Designer will be built in release mode, so in this case your plugin needs to be built in release mode too. When loading plugins they need to have the same configuration as the application and the Qt library that the application is using.


Why are .pro files parsed three times?

This is by design. The default configuration on Windows is debug_and_release, and this results in qmake parsing the .pro file multiple times: once for debug, once for release, and once for the master makefile. Note that qmake also generates three files:

  • Makefile
  • Makefile.debug
  • Makefile.release


On Redhat systems I get some Japanese characters displayed correctly but not all of them. How do I fix this?

On Redhat systems, when some of the Japanese characters are displayed correctly, but the rest are not, this indicates that Redhat was installed without Japanese font support. The only way to fix this is to install Japanese support. Then all Japanese characters should be visible just fine.


How do I get a non-rectangular or transparent widget?

Use QWidget::setMask() http://doc.qt.io/qt-5/qwidget.html#setMask.

Warning: Non-rectangular widgets are slow on some platforms.


How can I temporarily disable tooltips in a QTreeWidget?

You can reimplement QAbstractItemView::viewportEvent() http://doc.qt.io/qt-5/qabstractitemview.html#viewportEvent and handle the tooltip events the way you want there. Alternatively, you can install an event filter http://doc.qt.io/qt-5/qobject.html#eventFilter and handle the tooltip events there.



I am unable to set a fixed size on my dialog, how can I do this?

If your dialog does not have a layout, then you can simply call setFixedSize() http://doc.qt.io/qt-5/latest/qwidget.html#setFixedSize on it. If your dialog does have a layout, then you need to call

layout()->setSizeContraint(SetFixedSize)

This will take any changes of the size hint into consideration, i.e. when the user moves a toolbar from top to left in the window, then the fixed height will be smaller, but the fixed width will be bigger to take this into account.


I change the background color of my child widgets, but the color does not change. What's wrong?

To make real subwidget transparency possible, the widgets are transparent per default. If you want to change this then you need to set autoFillBackground http://doc.qt.io/qt-5/qwidget.html#autoFillBackground-prop to true in order to allow child widgets to have a different background color than the parent.


Building Qt with MinGW fails

If building Qt or Qt programs fails with something like the following errors:

_cd tools\moc && c:/MinGW/bin/mingw32-make.exe_
_/usr/bin/sh: cd: toolsmoc: No such file or directory_

Make sure sh.exe is not in your path. make will use sh.exe instead of Windows' standard shell if sh.exe is in the path. Unfortunately sh.exe does not understand Windows-style paths and discards the separator. There's not much Qt can do to work around this make feature. Both Cygwin and MSYS provide sh.exe. Avoid MSYS while building Qt or Qt programs.


I am trying to build Qt on the Mac with the -universal flag specified, but it fails. What's wrong?

If you are building Qt on a PowerPC you need to specify the sdk path as well as the universal flag because the default libraries installed on Tiger do not include Intel, i.e:

-universal -sdk /path/to/MacOSX10.4u.sdk

If you don't specify the sdk path on a PowerPC then it will fail giving a warning like:

/usr/lib/gcc/i686-apple-darwin8/4.0.1/libstdc++.dylib does not
contain an architecture that matches the specified -arch flag: i386

You also need to specify the sdk in the .pro file when you are building your application. Add:

QMAKE_SDK_PATH = /path/to/MacOSX10.4u.sdk

When using Qt with STL it crashes with a memory access exception, how do I fix this?

If this happens, then the problem is usually either one of two things:

  • A mismatch of runtime libraries - If you have built Qt in release mode and

your application in debug mode this means that it will be using two different runtime libraries. A release C runtime for Qt and a debug C runtime for your application. This means that there are two heaps in use and as a result if objects get passed from one heap to another (i.e. from Qt to the application and vice versa) then memory corruption will occur. You can usually catch this at build time, if you see a link warning about default libraries then this is usually indicitive of this problem. The only way to resolve it is to ensure that Qt and your application is built in the same mode. With Qt 4, by default both versions are available so you should not encounter this problem.

  • The environment variables are not set correctly - If you have more than

one compiler installed on your machine, then it is possible that the environment variables (particularly INCLUDE and LIB) are not pointing to the right compiler. You should ensure that the environment variables match the compiler that you are actually using to build and run the application.


How can I add SSL support to my Qt application?

For legal reasons, Qt doesn't ship with SSL. Only the Qt module that wraps SSL is included in the binaries. See the documentation http://doc.qt.io/qt-5/requirements.html.

If you want to include SSL support, you must first obtain OpenSSL from here http://www.openssl.org/ and make sure the paths to its include and lib directories are available in the environment when building Qt. OpenSSL support should then be available by default when building Qt.


How can I have richtext in my QTableView?

The standard table view doesn't support rich text formatting, but you can set an item delegate on the view and reimplement its paint function so that it will allow rich text. The paint() http://doc.qt.io/qt-5/qstyleditemdelegate.html#paint function below illustrates how this can be done and can be used with the qt\examples\itemviews\spinboxdelegate example http://doc.qt.io/qt-5/4.7/itemviews-spinboxdelegate.html :

void SpinBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
     QTextDocument document;
     QVariant value = index.data(Qt::DisplayRole);
     if (value.isValid() && !value.isNull()) {
          QString text("<span style='background-color: lightgreen'>This</span> is highlighted.");
     text.append(" (");
     text.append(value.toString());
     text.append(")");
     document.setHtml(text);
     painter->translate(option.rect.topLeft());
     document.drawContents(painter);
     painter->translate(-option.rect.topLeft());
}
}

You can find more information on the text formatting in our documentation http://doc.qt.io/qt-5/richtext-html-subset.html



Can I use Windows APIs together with Qt? The compiler complains about redefinition of HDC etc.

Yes, you should be able to use the Windows APIs alongside Qt without any problem. If you get such compilation failures, just make sure that you include the Qt header files before windows.h or any other Windows header files in your code.


Is there a limit to the number of widgets I can create on Windows ?

Qt does not have any limits in that respect, but of course the operating system/graphics subsystem does and Qt cannot work around those. For example, on Windows 2000/XP you are usually limited to about 10000 GDI objects, which includes widgets, pixmaps, fonts and cursors etc.

In Qt 4 widgets or pixmaps do not use GDI objects. Widgets still have some system dependent part, the window id, which also limits us in the number of widgets one can create at the same time. Since Qt 4.4 we only allocate window id's for toplevel widgets or widgets that otherwise explicitly need the window id. The effect of this is that you should seldomly reach the limit.

When the limit is reached, it is most likely because the application uses too many pixmaps, fonts, widgets or cursors and keep them alive at the same time. The only way to work around these limitations is to minimize the simultaneous use of these types of objects, such as deleting dialogs immediatly after they have been used and hidden, etc.


A QTreeWidget is sorted alphabetically by default, how can I change this behavior, e.g to sort numerically instead ?

You can achieve this by subclassing QTreeWidgetItem and reimplementing QTreeWidgetItem::operator<() http://doc.qt.io/qt-5/qtreewidgetitem.html#operator-lt to perform e.g numeric sorting rather than string comparison.

Note that setSortingEnabled http://doc.qt.io/qt-5/latest/qtreeview.html#sortingEnabled-prop should be set to true after you insert the items, otherwise the insertion will be slow as each item that gets inserted will get sorted. Alternatively, you can insert all of the items in one go using a list, see:

http://doc.qt.io/qt-5/qtreewidget.html#insertTopLevelItems

The following example illustrates how this can be done:

#include <QtGui>  
 
class TreeWidgetItem : public QTreeWidgetItem
{  
public:
    TreeWidgetItem(QTreeWidget *tree) : QTreeWidgetItem(tree)  {}
    TreeWidgetItem(QTreeWidget * parent, const QStringList & strings) 
                   : QTreeWidgetItem (parent,strings)  {}   
    bool operator< (const QTreeWidgetItem &other) const    
    {   
        int sortCol = treeWidget()->sortColumn();   
        int myNumber = text(sortCol).toInt();   
        int otherNumber = other.text(sortCol).toInt();   
        return myNumber < otherNumber;  
    }
};  
 
int main(int argc, char **argv) 
{  
    QApplication app(argc, argv);
    QTreeWidget tree;    
    tree.setColumnCount(2);   
    TreeWidgetItem *item1 = new TreeWidgetItem(&tree);  
    item1->setText(0, "1");  
    TreeWidgetItem *item2 = new TreeWidgetItem(&tree);  
    item2->setText(0, "2");  
    TreeWidgetItem *item3 = new TreeWidgetItem(&tree);  
    item3->setText(0, "3");   
    QStringList list;  
    list << "10" << "6";  
    TreeWidgetItem *item4 = new TreeWidgetItem(&tree, list);
    QStringList list2;  
    list2 << "20" << "7";  
    TreeWidgetItem *item5 = new TreeWidgetItem(&tree, list2);                  
    tree.setSortingEnabled(true);
    tree.show();  
    return app.exec();     
}

Are there any books about Qt programming?

Yes, there are quite a few books on Qt, most of them are available from amazon.com. Check out the Qt Book list to find a list of known available Qt books.


How can I change the border color of a frame using a stylesheet?

In order to change the border color, you need to specify a px size in the stylesheet http://doc.qt.io/qt-5/latest/stylesheet.html, e.g

browser->setStyleSheet("QTextBrowser {border: 1px solid red}");

The border is 0px by default, so in order for it to show up, you need to define a px size.


There are general rendering problems when I run my application on a machine that has a Matrox G450 graphics card. Other machines that don't use this card do not have this problem. Is there a way to workaround this?

This is due to a problem with the graphics card itself and not with Qt.

In order to workaround the problem, you need to disable one of the options on the card. There is an option on the Matrox G450 graphics card called **Use Bitmap Device Caching**. Disabling this should resolve the problem with the rendering.


I want to pop up a menu when I get a mouse event, but the menu pops up at wild places. (How do I convert local coordinates to global ones?)

The QPoint() http://doc.qt.io/qt-5/latest/qpoint.html argument to the popup() http://doc.qt.io/qt-5/latest/qmenu.html#popup function takes global screen coordinates as its argument. The position sent to a mouse event is always in the widgets local coordinates. Positions can be transformed between the different coordinate systems with either:

In the case with the mouse event, the correct way is to use the event's globalPos() http://doc.qt.io/qt-5/latest/qmouseevent.html#globalPos function instead. Here is one way of doing it:

void CustomWidget::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == RightButton)
        menu->popup(event->globalPos());
}

You frequently say that you cannot add this or that feature because it would break binary compatibility. What does this mean, really?

Binary compatibility means that you can safely distribute your Qt programs dynamically linked to the Qt library. If the users of your program have a newer version of the Qt dynamic library installed (or later upgrade to one), your program will still work. This can save much time, network, disk, and memory resources and administration work, for both you and the users of your Qt-based programs.

Technically, this means, roughly ordered from least to most obvious:

  • We cannot add reimplementations of virtual functions, unless it it safe

for older binaries to call the original implementation. This is because the compiler evaluates SuperClass::virtualFunction() calls at compile-time, not at link-time.

  • We cannot add or remove virtual member functions. This would change the

size and layout of the vtbl of every subclass.

  • We cannot change the type of any data members or move any data members

that can be accessed via inline member functions.

  • We cannot change the class hierarchy, except to add new leaves.
  • We cannot add or remove private data members. This would change the size

and layout of every subclass.

  • We cannot remove public or protected member functions unless they are

inline.

  • We cannot make a public or protected member function inline.
  • We cannot change what an inline function does, unless the old version

continues working.

  • We cannot change the access rights (i.e. public, protected or private) of

a member function. Some compilers mangle the access rights into the function name.

  • We cannot change the signature of a function, this includes changing the

return type and adding a new parameter.


How can I generate .vcproj files recursively for a .pro file with the SUBDIRS template set?

You can create .vcproj files recursively by typing

   qmake -tp vc -r

in the toplevel directory. Then the .vcproj files will be created in each subdirectory and the .sln file will be created in the main directory.


How can I get a HDC handle?

You can create a HBITMAP using GDI and then you can convert this to a QPixmap http://doc.qt.io/qt-5/latest/qpixmap.html afterwards. See the documentation http://doc.qt.io/qt-5/qpixmap.html#fromWinHBITMAP for more information on how to do that.


MSVCRTD.lib(cinitexe.obj) : warning LNK4098: defaultlib msvcrt.lib conflicts with use of other libs; use /NODEFAULTLIB:library -- What does this mean and how can I fix it?

This happens because Qt is linked against the release version of the C runtime and your application is built with debug symbols. You need to rebuild Qt in debug mode or the application in release mode.


Is there a way to work around the fact that the dockwindow is only hidden and not closed?

It is intentional that the dockwindow is hidden and not closed. You can delete the dockwindow by calling close() http://doc.qt.io/qt-5/latest/qwidget.html#close in the hideEvent() http://doc.qt.io/qt-5/latest/qwidget.html#hideEvent in addition to passing in the Qt::WA_DeleteOnClose http://doc.qt.io/qt-5/latest/qt.html#WidgetAttribute-enum attribute. Another approach could be to call deleteLater() http://doc.qt.io/qt-5/latest/qobject.html#deleteLater in the hideEvent(). You can not delete it in the hideEvent() as this will cause a crash.


Is there a limitation on Windows as to how many QRegions we can have?

Qt itself does not impose a limit on the number of QRegions http://doc.qt.io/qt-5/latest/qregion.html, however since QRegion uses a GDI object on Windows, you are limited by the amount of GDI resources that are available to you on Windows. This varies depending on what version of Windows you are using.


How can I create a QDialog that has no minimize, maximize and close buttons in the titlebar?

You can achieve this by specifying a combination of window flags http://doc.qt.io/qt-5/qt.html#WFlags-typedef provided your window manager supports those flags.

The example below demonstrates how this can be done, if this example does not remove the buttons for you, then it is likely because your window manager does not support that, and there is nothing we can do about that in Qt unfortunately.


#include <QtGui>
 
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QDialog box(0, Qt::WindowTitleHint);
    box.show();
    return app.exec();
}

How can I maintain several configurations using only one source tree?

This can be done by using shadow builds. Start with a clean Qt source directory. Create a folder for your custom configuration, and call configure from this directory using

../path/to/qtdir/configure -prefix $PWD <other options here>

This will allow you to maintain several configurations for one source.

My underlines for accelerators don't show up in the context menus when I press Alt, while they do for normal menus. What's wrong?

Context menus behave differently from normal menus, pressing Alt will not show the underlines in a context menu. Instead you need to change one of the settings in the control panel to make them visible. On Windows 7 this can for example be done here:

  • Control Panel / Ease of Access Center / Make the Keyboard easier to use*

Then you can find this option at the bottom of the window:

  • Underline keyboard shortcuts and access keys*

Check this if you want the underlines to be displayed at all times. You will see the same behavior in e.g notepad


How to build pdb for release version of Qt?

In order to build .pdb files for the release version of Qt, simply add the required compiler parameter in the mkspec you use. For example for MSVC 2005, you'd modify <Qt path>\mkspecs\win32-msvc2005\qmake.conf and add the -zi flag to QMAKE_CFLAGS_RELEASE and the /DEBUG flag to QMAKE_LFLAGS_RELEASE, e.g

QMAKE_CFLAGS_RELEASE    = -O2 -MD -zi

and

QMAKE_LFLAGS_RELEASE    = /INCREMENTAL:NO /DEBUG

Now the compiler will create debug information and the linker will use it while linking.


Do you provide a tool for creating graphs?

We do not provide graphs, but you can paint them yourself using QPainter. An example of a chart is available in the Qt directory in :

examples/itemviews/chart

Since the release of Qt 4.2 this is greatly facilitated by the QGraphicsView classes, although these offer functionality beyond that required by a simple graph.

There are also 3rd party classes that provide such functionality. See:

http://sourceforge.net/projects/qwt/ http://www.kdab.com/products/kd-chart


I am unable to step into the Qt code in Visual Studio, what can the problem be?

If you configured Qt with debug symbols then this should work. In addition to letting you step into the code this will also give output from asserts, warnings etc.

Also make sure your project has *CONFIG+= debug* in the .pro file.

The other situation where the debugging would not work is when something is out of sync. You are using some libraries from previous builds for example. The best thing to do in this case is to clean out the old build by going to a command prompt and typing

nmake clean
configure -redo
nmake

in your Qt directory.


Why do ActiveQt controls no longer work after an upgrade to Internet Explorer 7?

The reason this happens is because Internet Explorer 7 has changed the security settings around. In order to make ActiveQt controls work in Internet Explorer you need to add the website that hosts the control to your *Trusted Sites* and *Enable Scripting For Unsigned Controls* for the Trusted Sites security level.


Do you support using Qt in the Cygwin shell on Windows?

We don't support the Cygwin shell with Qt, mainly because Cygwin uses different directory separators than the Windows ones, therefore our apps are not likely to work correctly. You should use the cmd shell instead.


When untaring the Qt package the following warning is seen Tar.gz file content file @Longlink with zero permission and size. How can this be resolved?

When untarring the Qt package with a different version of tar that is not the GNU tar, then the warning:

Tar.gz file content file @Longlink with zero permission and size

may be seen. This is because LongLink is used when creating the package and this is an extension to GNU's tar to allow filenames longer than 100 characters. Therefore the package can only be used with the GNU version of tar, not with the vendor version of tar.


The font Rendering is distorted on Windows, what could cause this problem?

Ensure that ClearType is enabled in Windows display properties. The location of the ClearType check box depends on which version of Windows is being used.


When I compile my Qt based program I get a parse/syntax error in one of Qt's header files. What's wrong?

The most common cause is that a header file you have included before the Qt header file defines a macro with a name that is used in the Qt header file. Examples we have encountered include Ok, ButtonMask, list, red, black, bool, raise and connect.

A standard trick for tracking down these kind of problems is to look at compiler output after preprocessing has been done (often done with a -E option) and compare the output with the header file where you get the error.

There are three common strategies for dealing with such problems, which may often be combined:

  • Include the Qt header file first. This allows the other header file to #define the macro, and you cannot use Qt's function or enum.
  • Include the other header files, then #undef the relevant macro, then include the Qt header files. For example:

</code>

  1. define ButtonMask ButtonMask_hack
  2. include <offender.h>
  3. undef ButtonMask
  4. include <qmsgbox.h>

</code> This allows you to use the function or enum in Qt, but not the macro in the other header file.

  • Include the other header file in just one .cpp file (and no .h files) in

your application and encapsulate the functionality you need. This limits the scope of the conflict to just one .cpp file. Since this limits the system dependent code to one file, it also increases the portability of your code.

GNU STL is a special case. It defines two global enums, red and black, which are used by their internal red-black tree class. Unfortunately, they crash with Qt's global color objects named red and black. Here's a workaround:

#define red   stl_red
#define black stl_black
#include <stl.h>
#undef red
#undef black
#include <qcolor.h>

How is configuration management handled?

Standard unix configure; make; make install procedure is used. Specifically, the configure step enables options then the Qt qmake tool builds makefiles, which then control the build process. The specifics of each applications are encapsulated in a simple 'project' file (eg. listing files appropriate for given configurations).


Why does a statically built Qt use the dynamic Visual Studio runtime libraries ? Do I need to deploy those with my application ?

Qt is built using the -MD(d) switch, which links against the dynamic C/C++ runtime libraries. This is necessary as we have experienced memory problems when using anything but the -MD(d) flag, and in general, it is recommended to use. You should not alter this flag yourself for your application, because it conflicts with how the Qt library is built if you change the flag to -MT. You should not change it for Qt either, since it is likely to cause problems.

Qt is still built statically when using the -static option though, meaning you do not need to distribute the Qt dlls when deploying your application. You will have to distribute the C runtimes though (if they don't already exist on the target machine), see our deployment documentation http://doc.qt.io/qt-5/deployment-windows.html#application-dependencies.

If you choose to change this setting anyway, then it can be done in the qmake.conf file for your qmakespec. Where it says *-MD* you need to change it to be *-MT*. For Visual Studio 2005 it is also necessary to change the relevant files in mkspecs/features to remove the call to mt.exe. As stated above, we can't support you with any problems you run into as a consequence of making these changes.


What do I need installed on my machine to begin using Qt Creator and/or the Qt SDK?

The Qt SDK contains all the Qt-related components you need to get started, however some platform-specific essentials are also required depending on the platform you're developing on.

  • Windows: The Qt SDK contains everything you need.
  • Linux: The essential components to build software, which typically include make tools, gcc compiler, gdb debugger and the libraries needed for standard development.
  • Mac: Standard development tools like debugger, etc. The easiest way to get these is to install XCode.


When I read a XPM image into a QImage, is there a way I get determine which color is the transparent one?

You can have a look at the color table for the image. This is accessible through QImage::color() http://doc.qt.io/qt-5//qimage.html#color and then you can check for colors that have an alpha of 0.



How do I find out the properties of my Linux Frame Buffer?

Use the Linux command: *fbset*, often found in /usr/sbin/.


How can I find out where the contents of my Mac binary package is installed?

You can check where things are installed by going to the

  • /Library/Receipts/Qt_*.pkg/Contents *

directory and doing a lsbom on Archive.bom in that directory.


How can I create a custom editor in my view?

You can create a delegate and set it on the view using setItemDelegate() http://doc.qt.io/qt-5/qabstractitemview.html#setItemDelegate. A delegate http://doc.qt.io/qt-5/latest/qstyleditemdelegate.html allows the way items of data are rendered and edited to be customized.

Alternatively you can use QItemEditorCreatorBase http://doc.qt.io/qt-5/qitemeditorcreatorbase.html.

See the spinboxdelegate http://doc.qt.io/qt-5/latest/itemviews-spinboxdelegate.html example for a demonstration on how to implement your delegate.



Purify complains about UMRs (Uninitialized Memory Reads) in the QGDict constructor? Is this a bug in Qt?

This is not a bug in Qt. You can safely ignore this message.

QGDict uses bit field members to save space. When QGDict initializes its members, bits are either set or cleared. To clear a bit on assembly level, a byte is first read, AND'ed with a mask and written back. Purify reports a UMR when reading the byte. The UMR depends on your compiler and compiler options.

We've seen such false UMRs in these places, among others, in Qt:

  • QGDict::QGDict()
  • QMenuData::QMenuData()
  • QPushButton::init()
  • QMenuItem::QMenuItem()
  • QScrollbar::QScrollbar()

We've been in contact with PureAtria (now Rational), the maker of Purify, and they say this is a problem which cannot easily be solved. The only solution would be that the compiler first sets all bytes to zero before accessing the bits.


How is your double buffering implemented?

We use an approach commonly referred to as backing store. In this technique we maintain one pixmap per toplevel widget and each widget draws itself into this pixmap. Only when a widget changes does it update the contents of the toplevel pixmap. The effect of this is that on expose events the windowing system (or Qt) can copy the pixmap to screen rather than calling QWidget::paintEvent() (which can be costly), resulting in very fast updates when windows are moving on top of each other.


Is Qt binary compatible?

Qt is backwards binary and source compatible within each major release. This means that a program linked dynamically to e.g Qt 4.5.1 will continue running with Qt 4.5.3 without the need to recompile. Qt is not binary compatible between major versions such as Qt 2.x, Qt 3.x and Qt 4.x etc. Qt is also not forwards compatible, meaning that applications created with a newer version of Qt will not necessarily run or compile against older Qt versions.


How can I find out what image formats my application supports?

You can use QImageReader::supportedImageFormats() http://doc.qt.io/qt-5/qimagereader.html#supportedImageFormats for this.



Drawing dotted lines seems slow, do you have a solution for this?

When you are drawing dotted lines or lines that are of non zero width, these are slower than simple lines. One suggestion that could speed this up for you, is to instead of using a dotted line, use a pattern brush with Dense4Pattern as color for the pen and draw a solid line of width 0. This will give you the same result visually, but will use a faster path through the paint engine. Another alternative is to use an alpha color on the pen instead of a dotted line. This will be visually different, but usually looks as nice.


How can I paint outside the paintevent?

In Qt 4 it is not allowed to paint outside the paint event. The primary reason for this is that Mac OS X does not support it and it prevents us from doing widget composition which is one of the main features of Qt 4.1. What you can do instead is to do all your drawing to a QPixmap and draw this pixmap as part of your paint event.


How can I resize a QDockWidget programatically?

When you add the dock widget to the QMainWindow http://doc.qt.io/qt-5/latest/qmainwindow.html, it becomes part of the main window's layout and any size you give is ignored. You can however reimplement the QWidget::sizeHint() http://doc.qt.io/qt-5/latest/qwidget.html#sizeHint-prop for the widget contained in the QDockWidget http://doc.qt.io/qt-5/latest/qdockwidget.html to give it a preferred size or you can call QWidget::setFixedSize() http://doc.qt.io/qt-5/latest/qwidget.html#setFixedSize on it to give it a size that can't be changed.

Note that since QDockWidget acts as a wrapper for its child widget, custom size hints, minimum and maximum sizes and size policies have to be implemented in the child widget. QDockWidget will respect them, adjusting its own constraints to include the frame and title. Size constraints should not be set on the QDockWidget itself, because they change depending on whether it is docked; a docked QDockWidget has no frame and a smaller title bar.

See the following example for a demonstration:

#include <QtGui>  
 
class Label : public QLabel 
{ 
public:     
    Label(QWidget *parent) : QLabel(parent)
    {               
        setAutoFillBackground(true);
        setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        QPalette pal = palette();               
        pal.setBrush(QPalette::Window, Qt::red);                
        setText("The label");           
        setPalette(pal);
    }       
 
    QSize sizeHint() const
    {           
        return QSize(400, 500);     
    } 
};
 
int main(int argc, char **argv) 
{     
    QApplication app(argc, argv);
    QMainWindow box;     
    box.setCentralWidget(new QLabel("Central Widget", &box));
    QDockWidget *dock = new QDockWidget(&box);     
    dock->setWidget(new Label(dock));     
    box.addDockWidget(Qt::TopDockWidgetArea, dock );
    box.show();     
    return app.exec();     
}

When I build Qt I see the following: *** [listboxeditor.h] Trace/BPT trap and it fails to build.

This is because your DYLD_LIBRARY_PATH is not set correctly, it needs to include the $QTDIR/lib directory.


How can I add widgets to my QFileDialog instance?

You can use the layout() http://doc.qt.io/qt-5/qwidget.html#layout function to get hold of the dialog's layout and add your widgets there. See the following example:

    #include <QtGui>
 
    int main(int argc, char **argv)
    {
        QApplication app(argc, argv);
        QFileDialog box;
        QPushButton *button = new QPushButton(&box);
        button->setText("New button");
        QGridLayout *layout = (QGridLayout*)box.layout();
        layout->addWidget(button, 0, 0);
        box.show();
        return app.exec();
}

How can I draw text that is both filled and outlined?

If you want to draw text both filled and outlined, you can use QPainterPath http://doc.qt.io/qt-5/latest/qpainterpath.html for this, for instance:

    QPainterPath path;
    path.addText(position, font, "Hello");
    painter.setPen(pen);
    painter.setBrush(brush);
    painter.drawPath(path);


Purify found a memory leak in qapplication_x11.cpp. Why don't you clean up the XIM (X Input Method) structure?

This is to work around a bug in some versions of Xlib. The leak isn't harmful, it concerns only 400 bytes of memory which will be deallocated anyway when the application terminates.


You say I can program for multiple platforms with one source tree with Qt. Do I need cross-compilers or special tools?

Qt uses native compilers such as gcc (Linux) or Visual C++ (Windows) on the targeted platforms. There is no need for special cross-compilers or additional tools.


Are any benchmarking and performance measurement tools used?

We use a combination of complete instrumented quantification (Valgrind/ Cachegrind) and specific manual instrumentation (event timing).


Why can't Qt Mac for Cocoa be configured with -static?

There are two reasons:

  1. Qt has a nib it must load in order to interact correctly with the native menu bar. It is possible to copy the nib into the resource directory of the resulting bundle, but it is up to the developer to do this.
  2. Qt uses categories http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocCategories.html#//apple_ref/doc/uid/TP30001163-CH20-SW1
to extend capabilities of the certain Cocoa classes. These categories are lost when creating a static library. We are aware of a possible workaround(workaround) http://developer.apple.com/qa/qa2006/qa1490.html, but have not had a chance to try it out and support it.

We will evaluate and see if there is a possibility of supporting a static build with Cocoa in the future. For the time being it is not supported.


unixODBC FreeTDS qGetStringData: Error while fetching data

When installing unixODBC 2.2.14 and freeTDS 0.82 and executing a query like

 select USER_ID from MY_TABLE

the following message will be issued:

qGetStringData: Error while fetching data ( [FreeTDS][SQL Server]Program type out of range )

The solution to this problem is to install the latest version of FreeTDS, as it now provides SQL W CHAR.


Why is my text not antialiased?

Text antialiasing in Qt is based on the underlying font system. If a font is not being antialiased it is most likely because it is a bitmap font or because the underlying system does not support it. On X11 for instance, Xft is required to draw antialised fonts.

It is possible to specify a style strategy to QFont http://doc.qt.io/qt-5/latest/qfont.html, using QFont::StyleStrategy http://doc.qt.io/qt-5/latest/qfont.html#StyleStrategy-enum, which can be a hint to tell the font not to use a bitmap font. Depending on the fonts available on the system and the font family specified, this may or may not work.

On Windows 2000 fonts are usually not antialiased within a certain range (say sizes 8-16) to make text more crisp and readable.


How can a QModelIndex be retrived from the model for an internal data item?

In order to get a QModelIndex from the model for an internal data item there are 3 options to consider:

    • Option 1: Use unique identifiers**

Add a member to each item in the data structure that is used to store a unique identifier for the item. Then reimplement QAbstractItemModel::data() to return that value for a custom item data role that you can specify for your model. Now you can use QAbstractItemModel::match() to retrieve the QModelIndex for your item, using the unique identifier as a search parameter. If you have editable items, you should reimplement setData() as well.

Please see the following web pages for more information:

http://doc.qt.io/qt-5/qabstractitemmodel.html#data http://doc.qt.io/qt-5/qabstractitemmodel.html#match http://doc.qt.io/qt-5/qt.html#ItemDataRole-enum http://doc.qt.io/qt-5/qabstractitemmodel.html#setData

    • Option 2: Use QPersistentModelIndex**

Create a QPersistentModelIndex for each item you wish to keep track of when you add the item to the model. QPersistentModelIndex can be stored, and it is used to keep a reference to an item that is valid for as long as the item can be accessed by the model. The QPersistentModelIndex can be used as a QModelIndex.

Please see the following web pages for more information:

http://doc.qt.io/qt-5/qpersistentmodelindex.html

    • Option 3: Traverse the model from the root item**

Store a pointer to your item's parent, if it has any. Then store pointers to the parent's parent all the way up to the root item. Once you have found the root item, you can start traversing the model, using QAbstractItemModel::index(). For each returned index, compare its internal pointer with the pointer of the ancestor of your item, and if they match, you can repeat the process, calling index() with the newly found model index, in effect dropping down one level in you data structure and getting closer to your item. When the internal pointer of a model index matches that of your item's parent, you call index() one last time with that model index as the argument, and you should get the QModelIndex for your item. Please consider that in a worst case scenario you will traverse the whole data model.


How to avoid subclassing all available styles when wanting to change a small aspect of a widget for all styles

The way to do this is to utilize a proxy style, this was originally mentioned way back in Qt Quarterly 9 (all those years ago) using a class that subclasses QStyle http://doc.qt.io/qt-5/latest/qstyle.html and had a member variable which would point to the original style being used. For the curious the article can be found here http://doc.qt.io/qt-5/qq/qq09-q-and-a.html#style.

On the face of it, this looks like it will do the trick, and it looks nice, however it is not as robust as it appears. The problem with this approach is due to the fact that inside the styles themselves they call the style functions directly. For instance in QWindowsStyle::drawControl() http://doc.qt.io/qt-5/latest/qstyle.html#drawControl it will call styleHint() http://doc.qt.io/qt-5/latest/qstyle.html#styleHint directly meaning it won�� call your reimplemented styleHint() function in the ProxyStyle class and its turns out to not be so useful at all anymore.

So the problem still remains, how do we make this smarter? The proxy style approach is still the one we want to go with as this will give the result we want, however its the implementation of it that we need to change to cope with the situation better. Therefore we need to somehow have subclasses of the existing styles that use the proxy style approach.

Firstly we create a ProxyStyle class that isn�� a subclass of QStyle (all will make sense later I promise :) In this example I want to change all styles to always underline shortcuts so to do this I need to reimplement styleHint() in the styles.

class ProxyStyle
{
public:
    ProxyStyle(const QString &baseStyle) { style = QStyleFactory::create(baseStyle); }
    int proxyStyleHint(QStyle::StyleHint hint, const QStyleOption *option = 0,
                             const QWidget *widget = 0, QStyleHintReturn *returnData = 0) const
    {
        if (hint == QStyle::SH_UnderlineShortcut)
            return 1;
        return style->styleHint(hint, option, widget, returnData);
    }
private:
    QStyle *style;
};

This is similar to the approach that is given in Qt Quarterly 9 except the difference is that we don�� have a styleHint() function but we have a proxyStyleHint() function, this is delibrate due to the following:

  1. define ADDSTYLESUBCLASS(BaseStyleClass, BaseStyleName) \
class My##BaseStyleClass : public BaseStyleClass, public ProxyStyle \
{\
public:\
    My##BaseStyleClass() : BaseStyleClass(), ProxyStyle(BaseStyleName) {}\
    int styleHint(StyleHint hint, const QStyleOption *option = 0, const QWidget *widget = 0, QStyleHintReturn *returnData = 0) const\
    {\
        return proxyStyleHint(hint, option, widget, returnData);\
    }\
};

This is where we are actually subclassing the styles themselves, it has been added as a macro because we want to make it easier to just add styles that a subclass should be provided for. So if for example a Windows 7 style was added in 4.6, it would be easy to update this relevant code. We only need to reimplement the functions that we are interested in, so in this case we add a styleHint() reimplementation that calls our proxyStyleHint() function.

So to make all styles available we just use the macro to define the classes like such (delibrately cut just for illustration purposes):

ADDSTYLESUBCLASS(QCleanlooksStyle, "cleanlooks");
ADDSTYLESUBCLASS(QPlastiqueStyle, "plastique");
ADDSTYLESUBCLASS(QMotifStyle, "motif");
ADDSTYLESUBCLASS(QWindowsStyle, "windows");
ADDSTYLESUBCLASS(QCDEStyle, "cde");

Now its possible to use MyQWindowsStyle and this will always call our proxyStyleHint() implementation even if its called from QWindowsStyle itself or directly on the style.

There is just one thing left to do to make this easy to replace any existing style either on a widget or on the application. In order to be able to determine which subclassed style should be used a function is added that utilizes qobject_cast to determine which one should be used (again cut for illustration purposes).

QStyle *returnSubclassStyleForBaseStyle(QStyle *baseStyle) {

   if (qobject_cast<QWindowsStyle *>(baseStyle)) {
       if (qobject_cast<QCleanlooksStyle *>(baseStyle)) {
  1. ifdef Q_OS_X11
           if (qobject_cast<QGtkStyle *>(baseStyle))
               return new MyQGtkStyle;
  1. endif
           return new MyQCleanlooksStyle;
       }
   ...
   if (qobject_cast<QMotifStyle *>(baseStyle)) {
       if (qobject_cast<QCDEStyle *>(baseStyle))
           return new MyQCDEStyle;
       return new MyQMotifStyle;
   }
   return baseStyle;

}

Leaving just one line needed to set the proxy style on the application in our example:

app.setStyle(returnSubclassStyleForBaseStyle(app.style()));

And there you have it, the application still looks native with the exception of the change that has been done in the style. The way that this is implemented makes it easy to add your own changes in, as you only need to change it in one place and also makes it easy to add support for new styles too.

Unfortunately there is a problem with this approach and that is that it does not work with styles that are implemented as plugins, the approach used here needs to be able to know about the classes themselves. So for example, this will not work exactly as expected when the KDE Oxygen style is used as the code does not know about this style. However, this problem would occur too if an application developer wanted to subclass the Oxygen style to make the change directly (without using the proxy style approach). If the Oxygen style can be linked against in some way then it would be possible to utilize this approach, since all that is needed is to be done is to add an ADDSTYLESUBCLASS line and add a couple of lines to the returnSubclassStyleForBaseStyle() function.

The whole code for the proxy style approach is available as an attachment.


How do I create tooltips in QHeaderView?

It is possible to create tooltips for each header in a model by setting its Qt::ToolTipRole http://doc.qt.io/qt-5/latest/qt.html#ItemDataRole-enum

    QStandardItemModel model ;
    model.setRowCount(5);
    model.setColumnCount(2);
    model.setHeaderData ( 1, Qt::Horizontal, QVariant("test"), Qt::ToolTipRole );
    model.setHeaderData ( 1, Qt::Horizontal, QVariant("Column 2"), Qt::DisplayRole );

How can I make Designer look for plugins outside qtDirectory\plugins\designer

You can make designer look for plugins elsewhere using the QT_PLUGIN_PATH http://doc.qt.io/qt-5/qcoreapplication.html#libraryPaths environment variable.

Note that your plugins need to be a in a designer subdirectory inside the path that you specify. See also the documentation on building and installing the plugin http://doc.qt.io/qt-5/designer-creating-custom-widgets.html#building-and-installing-the-plugin.



How can I change the width of the popup list in my combobox?

In order to change the width of the combobox's view, you can subclass QComboBox http://doc.qt.io/qt-5/latest/qcombobox.html and reimplement showPopup() http://doc.qt.io/qt-5/latest/qcombobox.html#showPopup to set the width you want on the view.

See the following example for an indication of how to do this:

#include <QApplication>
#include <QComboBox>
#include <QAbstractItemView>
 
class ComboBox : public QComboBox
{
public:
    ComboBox();
    void showPopup();
};
 
ComboBox::ComboBox() : QComboBox()
{
    addItem("one");
    addItem("some more text");
}
 
void ComboBox::showPopup()
{
    view()->setFixedWidth(400);
    QComboBox::showPopup();
}
 
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    ComboBox box;
    box.show();
    return app.exec();
}

How can I have both text and a pixmap on a QLabel?

This is not possible to achieve with the QLabel http://doc.qt.io/qt-5/latest/qlabel.html API directly, but you can use richtext to make this work. See the following example:

#include <QtGui>
int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  QLabel label;
  label.setText("<img src="fileopen.xpm"> labeltext");
  label.show();
  return app.exec();

How can I avoid a paintEvent() when focus changes on Windows ?

The trick is to block activate/inactive events. See the example below for a demonstration. Note that it is necessary to set the WA_OpaquePaintEvent http://doc.qt.io/qt-5/latest/qt.html#WidgetAttribute-enum attribute since widgets are defined to be transparent by default. This has been done to allow widgets to have features like antialiased round edges and sub widget transparency. A transparent widget needs to be updated when its parent is updated because an update in the parent will effect the child widget as well. This also applies to palette changes.

By setting the WA_OpaquePaintEvent the widget is no longer transparent and no longer subject to updates as a result of changes in the parent chain.

#include <QtGui> 
#include <stdio.h> 
 
class cDrawWindow : public QWidget 
{
public:
  cDrawWindow(QWidget *Parent) : QWidget(Parent)
  {
    setAttribute(Qt::WA_OpaquePaintEvent); 
  }
  void paintEvent(QPaintEvent *pe)
  {
    fprintf(stderr, "paintEvent ");
  }
  bool event(QEvent *e) 
  {
    switch (e->type())
    {
    case QEvent::WindowActivate:
    case QEvent::WindowDeactivate:
      return true;
    }
    return QWidget::event(e);
  } 
};
 
class cMainWindow : public QMainWindow 
{ 
private: 
  cDrawWindow *w;
public:
  cMainWindow(void) {
    w = new cDrawWindow(this); 
    setCentralWidget(w); 
    move(0, 0); } 
};
 
int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  cMainWindow mw;
  mw.show(); 
  return a.exec(); 
}

I have problems building an application that uses a Qt Designer plugin on Windows. Can you give some advice?

First of all, you need to export your class so that it can be used by the plugin, e.g:

class QDESIGNER_WIDGET_EXPORT button : public QPushButton

Also, make sure you have the Q_OBJECT macro in your class declaration, if you do not include it then the plugin will not have access to the correct QMetaObject which would have information about the class itself. As a result this would break the introspection of the plugin.

In the .pro file of your plugin you also need to give some extra information

TEMPLATE = lib

Make sure you specify the lib template since you are building a library.

DESTDIR = $$[QT_INSTALL_PLUGINS]/designer

In addition you need to specify where the plugin should be located. Qt will look in plugins/designer by default, so this is where your plugin should be.

An example .pro file may like look this:

TEMPLATE = lib
CONFIG+= designer plugin debug_and_release
LANGUAGE = C++
TARGET = buttonPlugin
SOURCES += buttonPlugin.cpp button.cpp
HEADERS += buttonPlugin.h button.h
DESTDIR = $$[QT_INSTALL_PLUGINS]/designer
CONFIG += qt warn_on release plugin

With your application you need to add the following to your application's .pro file:

LIBS+=$$[QT_INSTALL_PLUGINS]/designer/nameOfYourPlugin.lib

This line is necessary to link against the lib file and at runtime the application will use the dll. The lib file is located at $$[QT_INSTALL_PLUGINS]/designer since this is what was specified as the DESTDIR in the plugin's pro file.

INCLUDEPATH += text/example/yourPluginDir/yourWidget

You also need to specify the INCLUDEPATH, so that your application will be able to find your custom widget's header file.

An example .pro file can look as follows:

TEMPLATE = app
LANGUAGE = C++
LIBS += $$[QT_INSTALL_PLUGINS]/designer/buttonPlugin.lib
INCLUDEPATH += text/example/yourPluginDir/yourWidget
CONFIG += qt warn_on release
SOURCES += main.cpp
FORMS = form1.ui

Finally, your application also needs to be able to find the plugin's dll. This can be done either by putting the myPlugin.dll into the same directory as your application, or by adding the path to the myPlugin.dll to the PATH environment variable.


How can I create checkable items in a QTreeWidget?

In order to create checkable items in a QTreeWidget http://doc.qt.io/qt-5/latest/qtreewidget.html, you need to pass in the Qt::ItemIsUserCheckable http://doc.qt.io/qt-5/latest/qt.html#ItemFlag-enum flag to QTreeWidgetItem::setFlags() http://doc.qt.io/qt-5/latest/qtreewidgetitem.html#setFlags in addition to calling QTreeWidgetItem::setCheckState() http://doc.qt.io/qt-5/latest/qtreewidgetitem.html#setCheckState. See the following example for a demonstration:

#include <QtGui>
int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  QTreeWidget tree(0);
  tree.setColumnCount(1);
  QTreeWidgetItem *itemOne = new QTreeWidgetItem(&tree);
  itemOne->setFlags(itemOne->flags()|Qt::ItemIsUserCheckable);
  itemOne->setText(0,"Item one");
  itemOne->setCheckState(0, Qt::Checked);
  tree.show();
  return app.exec();
}

How can I avoid drawing the focus rect on my buttons?

In order to not draw the focus rect of the buttons it is necessary to subclass the style and reimplement QStyle::drawControl() http://doc.qt.io/qt-5/qstyle.html#drawControl to strip out the State_HasFocus http://doc.qt.io/qt-5/latest/qstyle.html#StateFlag-enum state for the buttons.

See the following example:

#include <QtGui>
 
class Style : public QWindowsStyle
{
public:
  Style()
  {}
  void drawControl ( ControlElement element, const QStyleOption * option,
    QPainter * painter, const QWidget * widget = 0 ) const
  {
    if(element == CE_PushButton) {
      const QStyleOptionButton *b = qstyleoption_cast<const QStyleOptionButton *>(option);
      QStyleOptionButton *btn = (QStyleOptionButton *)b;
      if (btn) {
        if (btn->state & State_HasFocus) {
          btn->state = btn->state ^ State_HasFocus;
        }
      }
      QWindowsStyle::drawControl(element, btn, painter, widget);
 
    } else {
      QWindowsStyle::drawControl(element, option, painter, widget);
    }}};
 
int main(int argc, char **argv)
{
  QApplication app(argc, argv);
 
  QWidget box;
  QPushButton *button1 = new QPushButton(&box);
  button1->setText("Number one");
 
  QPushButton *button2 = new QPushButton(&box);
  button2->setText("Number two");
 
  button1->setStyle(new Style());
  button2->setStyle(new Style());
 
  QVBoxLayout *layout = new QVBoxLayout(&box);
  layout->addWidget(button1);
  layout->addWidget(button2);
 
  box.show();
  return app.exec();
}

When the FileMode is DirectoryOnly in my QFileDialog, how can I select multiple directories?

By default it is only possible to select one directory when the FileMode http://doc.qt.io/qt-5/latest/qfiledialog.html#FileMode-enum is DirectoryOnly. You can change this by getting hold of the QListView http://doc.qt.io/qt-5/latest/qlistview.html and QTreeView http://doc.qt.io/qt-5/latest/qtreeview.html children of the QFileDialog http://doc.qt.io/qt-5/latest/qfiledialog.html and setting their selection mode to MultiSelection http://doc.qt.io/qt-5/latest/qabstractitemview.html#SelectionMode-enum.

See the following example:

#include <QtGui>
int main(int argc, char **argv)
{
    QApplication a(argc, argv);
    QFileDialog w;
    w.setFileMode(QFileDialog::DirectoryOnly);
    QListView *l = w.findChild<QListView*>("listView");
    if (l) {
         l->setSelectionMode(QAbstractItemView::MultiSelection);
     }
    QTreeView *t = w.findChild<QTreeView*>();
     if (t) {
       t->setSelectionMode(QAbstractItemView::MultiSelection);
   }
   w.exec();   
}

When converting my pixmap to a HBITMAP using toWinHBITMAP(QPixmap::PremultipliedAlpha ) , they appear with a black background. How can I give the icons a transparent background?

You need to use the GDI function AlphaBlend which supports proper alpha. When asking for PremultipledAlpha, you need to use AlphaBlend.

The following example demonstrates how this can be done:

#include <QtGui>
#include <qt_windows.h>
 
void drawHBITMAP(HDC dc, int x, int y, int w, int h, HBITMAP hbm)
{
  HDC bmdc = CreateCompatibleDC(dc);
  HGDIOBJ oldbm = SelectObject(bmdc, hbm);
  BLENDFUNCTION blend = { AC_SRC_OVER, 0, 255, AC_SRC_ALPHA };
  AlphaBlend(dc, x, y, w, h, bmdc, 0, 0, w, h, blend);
  SelectObject(bmdc, oldbm);
  DeleteDC(bmdc);
}
int main(int argc, char** argv)
{
  QApplication app(argc, argv);
  HBITMAP image1;
  QPixmap pix1( "somePixmap" );
  pix1.setMask( pix1.createHeuristicMask() );
  image1 = pix1.toWinHBITMAP(QPixmap::PremultipliedAlpha );
  HDC dc = GetDC(0);
  drawHBITMAP(dc, 100, 100, pix1.width(), pix1.height(), image1);
}

Note that you need to link against msimg32.dll.


How to compress data with Qt?

Qt uses the zlib library to provide compression. This means that you can compress and decompress your bytearrays of data using Qt. See the documentation on qUncompress() http://doc.qt.io/qt-5/qbytearray.html#qUncompress

Note that this does not produce file archives that can be opened by other applications, to do that you will need to write it yourself using Qt's custom file handling system http://doc.qt.io/qt-5/qabstractfileengine.html#details or use a 3rd party library.


How can I prevent the MDI subwindows from closing when pressing Ctrl+W?

You can stop the Ctrl+W shortcut from triggering by reimplementing the eventFilter() http://doc.qt.io/qt-5/qobject.html#eventFilter for your QMainWindow http://doc.qt.io/qt-5/latest/qmainwindow.html and returning true when the shortcut is Ctrl+W.

The event filter can be installed on the subwindows or on the application itself. Note that installing the event filter on the application will require more resources.

The example below illustrates how this can be done:

#include <QtGui>
 
class Object : public QObject
{
    Q_OBJECT
public:
    Object(QWidget *parent) : QObject(parent)
    {}
 
    bool eventFilter(QObject *obj, QEvent *event){
        if (event->type() == QEvent::ShortcutOverride) {
            QKeyEvent *ev = static_cast<QKeyEvent *>(event);
            if (ev->modifiers() == Qt::CTRL && ev->key() == Qt::Key_W) {
                QMessageBox::information(0,"shortcut notification", "You pressed Ctrl+W");
                //stop the event
                return true;
            }
        }
        // standard event processing
        return QObject::eventFilter(obj, event);
 
    }
};
#include "main.moc"
 
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QMainWindow window;
    QMdiArea *area = new QMdiArea(&window);
    QMdiSubWindow *first = area->addSubWindow(new QLineEdit(area));
    QMdiSubWindow *second = area->addSubWindow(new QLineEdit(area));
    window.setCentralWidget(area);
    Object *object = new Object(&window);
    first->installEventFilter(object);
    second->installEventFilter(object);
    window.show();
    return app.exec();
}

Compiling a Qt program fails with error messages looking something like this: undefined reference to `_vt.11QPushButton'

This usually means you have two different versions of the Qt library (libqt.so) installed on your system, and they interfere with each other. Either modify the compiler's library search path so that it finds your new Qt library first, or simply remove the old one.

It may also indicate that your Qt library was compiled with a compiler that is incompatible with the one you are using, e.g. gcc vs. egcs.

If you get this error trying to run a pre-compiled Qt program, it usually means that the program has been compiled with a version of Qt that is newer than the one on your system. Upgrade to the latest version of Qt.


Polling SQL connection to test connectivity.

There is currently a suggestion to add this feature as the one function that should serve this purpose doesn't currently do it.

http://bugreports.qt.io/browse/QTBUG-223

There isn't actually a signal or any other indicator to poll the status of a connection in this case. The workaround for this is to send a query that you know will always be returned true, and if it returns false, you will know that the connection is down.


QWebView does not display Chinese fonts from a Chinese web site

On X11 this problem can be solved by installing libFreetype and libFontconfig. These libraries are needed to render the true type fonts that contain these characters. On Windows you need to install the Chinese fonts from the Windows installation CD to get this to work.


How can I use QSound with ALSA ?

There is no ALSA support for QSound as ALSA only works in Linux. Qt uses its own sound server(QSS) that interacts with /dev/dsp directly. If you want to use ALSA on Linux, then implement it directly with the ALSA API or use Phonon.


Is there a Qt way to handle UNIX/POSIX signals?

There isn't a true Qt way because of the non-crossplatform nature of UNIX/POSIX signals, but you should be able to do it using QSocketNotifier. You can read more about this here:

http://doc.qt.io/qt-5/unix-signals.html


How can I move a window around when using Qt::FramelessWindowHint?

You need to reimplement the mouse event handlers for the widgets you would like be able to move your window with. Here is an example using QMenuBar http://doc.qt.io/qt-5/latest/qmenubar.html:

#ifndef CMENUBAR_H
#define CMENUBAR_H
 
#include <QMenuBar>
 
class QPoint;
class QMouseEvent;
class QWidget;
 
class CMenuBar : public QMenuBar
{
public:
    CMenuBar();
    CMenuBar(QWidget *par);
 
protected:
    void mousePressEvent(QMouseEvent *event);
    void mouseMoveEvent(QMouseEvent *event);
    void mouseReleaseEvent(QMouseEvent *event);
 
private:
    QPoint offset;
    bool moving;
};
 
#endif // CMENUBAR_H
 
#include "cmenubar.h"
#include <QPoint>
#include <QMouseEvent>
#include <QDebug>
 
CMenuBar::CMenuBar()
{
    moving = false;
}
CMenuBar::CMenuBar(QWidget *par)
{
    setParent(par);
    moving = false;
    setMouseTracking(false);
}
 
void CMenuBar::mousePressEvent(QMouseEvent *event)
{
    QMenuBar::mousePressEvent(event);
    if((event->button() == Qt::LeftButton) && !actionAt(event->pos())) {
        moving = true;
        offset = event->pos();
    }
}
 
void CMenuBar::mouseMoveEvent(QMouseEvent *event)
{
    QMenuBar::mouseMoveEvent(event);
    if(moving)
        parentWidget()->move(event->globalPos() - offset);
}
 
void CMenuBar::mouseReleaseEvent(QMouseEvent *event)
{
    QMenuBar::mouseReleaseEvent(event);
    if(event->button() == Qt::LeftButton) {
        moving = false;
    }
}

Antialiasing does not work with VNC

This is most likely due to lack of XRender support in the VNC Client. To get antialiasing to work you must either enable XRender support on the VNC Client, or use the raster paint engine. This can be done by starting the application with ./myApp -graphicssystem raster


On which operating systems does Qt Creator run?

Due to the nature of Qt, Qt Creator should eventually run on every platform supported by Qt. You can find an overview of the supported platforms here:

Supported platforms http://doc.qt.io/qt-5/qtcreator-2.1/creator-os-supported-platforms.html


What is the difference between a static and a shared build of the Qt library?

A shared Qt library makes it necessary to distribute the Qt DLL together with your software. Applications and libraries linked against a shared Qt library are small and can make use of components and plugins. All applications created with a static library will be at least 1.5MB in size and it is not possible to build or use any components or plugins with a static Qt library.


Moving my application away from MFC, why would I select Qt as the toolkit to move to?

The features of Qt in general are presented on the main product page. For moving an existing MFC application, the following facts are particularly relevant:

  • Qt is actively maintained and developed.
  • Qt lets you target multiple platforms (Linux, Unix, Windows, Mac) with a single source code base.
  • Qt is commercially developed and commercial support, training and consultancy services are provided.
  • The Qt API has an intuitive, logical design that makes it easy to learn and efficient to use.
  • Qt is a C++ toolkit, just like MFC. This means that the porting job will be much simpler, and allow for a much higher degree of code reuse, than than if porting to e.g. Java or .NET/C#.
  • Through the Qt/MFC Migration Framework, MFC applications can be partly and gradually ported to Qt. It is not necessary to do the entire port in one go.
  • Qt provides a consistent class API that covers both GUI and all the operating system functionality needed by most applications.


How can I prevent the clicked() signal from being emitted when I want to grab the doubleClicked() signal in my item view ?

Normally the clicked() signal will be emitted in addition to the doubleClicked() signal since you are actually clicking on the widget. The same happens with events when you double click on a widget, you get a press event, release event then a double click event. The press followed by the release indicates that a click occurred. If you don't want this behavior then you can start a timer in the mouseReleaseEvent() http://doc.qt.io/qt-5/latest/qabstractitemview.html#mouseReleaseEvent and then in the mouseDoubleClickEvent() http://doc.qt.io/qt-5/latest/qabstractitemview.html#mouseDoubleClickEvent kill the timer. If the timer times out, you can emit the clicked signal and stop the timer.

See the following example for an illustration:

#include <QtGui>
 
class TableWidget : public QTableWidget
{
    Q_OBJECT
public:
    TableWidget()
    {
        ignoreNextRelease = false;    
        timer = new QTimer(this);
        setColumnCount(3);
        setRowCount(3);
        connect(this, SIGNAL(cellClicked (int, int)), this, SLOT(testSlot()));
        connect(this, SIGNAL(cellDoubleClicked (int, int)), this, SLOT(testSlot2()));
        connect(timer, SIGNAL(timeout()), this, SLOT(emitClicked()));
    }
 
    void mouseReleaseEvent(QMouseEvent *event)
    {
        if (!ignoreNextRelease) {
            timer->start(QApplication::doubleClickInterval());
            blockSignals(true);
            QTableWidget::mouseReleaseEvent(event);
            blockSignals(false);
        }
        ignoreNextRelease = false;
    }
 
    void mouseDoubleClickEvent(QMouseEvent *event)
    {
        ignoreNextRelease = true;
        timer->stop();
        QTableWidget::mouseDoubleClickEvent(event);
    }
 
public slots:
 
    void testSlot()
    {
    qDebug("cellClicked() was emitted");
    }
 
    void testSlot2()
    {
        qDebug("cellDoubleClicked was emitted");
    }
 
    void emitClicked()
    {
        emit cellClicked(currentRow(), currentColumn());
        timer->stop();
    }
 
private:
    QTimer *timer;
    bool ignoreNextRelease;   
};
 
#include "main.moc"
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    TableWidget box;
    box.show();
    return app.exec();    
}

How can I draw custom subcontrols for a complex control ?

You can achieve this either by subclassing the style or by using a stylesheet http://doc.qt.io/qt-5/stylesheet.html. If you want to style the drop-down button of a combobox for example, then you can subclass the style and reimplement drawComplexControl() http://doc.qt.io/qt-5/qstyle.html#drawComplexControl to remove the existing button. Then after the style has done its painting, you can do your custom painting. See the following example:

#include <QtGui>
 
class Style : public QWindowsStyle
{
public:
  Style() {}
  void drawComplexControl(ComplexControl control, const QStyleOptionComplex *option, QPainter *painter, const QWidget *widget = 0 ) const {
    if (const QStyleOptionComboBox *group = qstyleoption_cast<const QStyleOptionComboBox*>(option)) {
      QStyleOptionComboBox newComboBox(*group);
      newComboBox.subControls &= ~QStyle::SC_ComboBoxArrow;
      // Let the style do its drawing
      QWindowsStyle::drawComplexControl(control, &newComboBox, painter, widget);
      // Do your own drawing
      QRect rect= subControlRect(control, option,SC_ComboBoxArrow, widget);
      QPixmap pix = standardPixmap(QStyle::SP_TitleBarMenuButton, option, widget);
      painter->save();
      painter->setBrushOrigin(rect.topLeft());
      painter->fillRect(rect, QBrush(pix));
      painter->restore();
    } else {
      QWindowsStyle::drawComplexControl(control, option, painter, widget);
    }}};
 
int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  QWidget widget;
  QVBoxLayout *layout = new QVBoxLayout(&widget);
  QComboBox *box = new QComboBox(&widget);
  box->insertItem(0,"one");
  box->setStyle(new Style());
  layout->addWidget(box);
  widget.show();
  return app.exec();
}

Other parts of the combobox can be modified by accessing the properties of the QStyleOptionComplex pointer passed in to drawComplexControl in the example above.

When using style sheets, then the drop-down button can be styled using the

drop-down sub-control and the arrow mark inside the drop-down button can be

styled using the ::down-arrow sub-control.See the documentation:

http://doc.trolltech.com/stylesheet.html#list-of-stylable-widgets

To see how this works, you can run the stylesheet example under yourQtVersion\examples\widgets\stylesheet and open the editor under File/Edit Style to see how the combobox is styled there.


How can I change the header text of my model based view?

In order to change the header text of a model based view you need to reimplement headerData() http://doc.qt.io/qt-5/qabstractitemmodel.html#headerData and return the text you want for the relevant section, orientation and row there.

#include <QtGui>
 
class Model : public QAbstractTableModel {
public:
  Model(QObject *parent)
  {
    QStringList firstRow;
    QStringList secondRow;
    for (int i = 0; i < 5; i++ ) {
      firstRow.insert(i,"Row 1 " + QString::number(i+1));
      secondRow.insert(i,"Row 2 " + QString::number(i+1));
    }
    stringList << firstRow << secondRow;
  }
 
// Returns the number of rows
int rowCount ( const QModelIndex & parent = QModelIndex() ) const
{
  return stringList.count();
}
// Returns the number of columns
int columnCount ( const QModelIndex & parent = QModelIndex() ) const
{
  return stringList[0].count();
}
// Returns an appropriate value for the requested section, orientation and role
QVariant headerData ( int section, Qt::Orientation orientation, int role) const
{
  if (role ==Qt::DisplayRole ) {
    if (section == 0 && orientation == Qt::Vertical ) {
      return QString("First");
    } else if (section == 1 && orientation == Qt::Vertical ) {
      return QString("Second");
    } else {
      return QVariant();
    }} else {
      return QVariant();
    }
}
 
// Returns an appropriate value for the requested data.
// If the view requests an invalid index or if the role is not
// Qt::DisplayRole, an invalid variant is returned.
// Any valid index that corresponds to a string for the index'scolumn and row in
// the stringlist is returned
 
QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const
{
  if (!index.isValid())
    return QVariant();
  if (role != Qt::DisplayRole)
    return QVariant();
  QStringList list = (QStringList)stringList.at(index.row());
  return list.at(index.column());
}
private:
QList<QStringList>stringList;
};
 
int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  QWidget widget;
  QHBoxLayout *layout = new QHBoxLayout(&widget);
  QTableView *tableView = new QTableView(&widget);
  Model *model = new Model(tableView);
  tableView->setModel(model);
  layout->addWidget(tableView);
  widget.show();
  return app.exec();
}

How can I create a dialog that can be closed programatically, but not by the user ?

You can achieve this by reimplementing closeEvent() http://doc.qt.io/qt-5/qwidget.html#closeEvent and then ignoring or accepting the event depending on a flag.

The following is an example of how to do this:

#include <QtGui>
 
class Dialog : public QDialog
{
    Q_OBJECT
public:
    Dialog();
    void closeEvent ( QCloseEvent * e );
public slots:
    void closeDialog();
private:
    bool ignoreCloseEvent;
};
 
Dialog::Dialog() : QDialog()
{
    ignoreCloseEvent = true;
}
 
void Dialog::closeEvent ( QCloseEvent * e )
{
    if (!ignoreCloseEvent) {
        QDialog::closeEvent(e);
    } else {
        e->ignore();
    }
}
void Dialog::closeDialog()
{
    ignoreCloseEvent = false;
    accept();
}
 
#include "main.moc"
 
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    Dialog dialog;
    dialog.show();
    return app.exec();
}

Is it possible for either the left or right dock areas to have full height of their side rather than having the bottom take the full width?

It is possible to get what you are looking for, but you have to be kind of sneaky about it. The real trick is to have a QMainWindow http://doc.qt.io/qt-5/latest/qmainwindow.html as the central widget of your QMainWindow and then dock bottom QDockWidget http://doc.qt.io/qt-5/latest/qdockwidget.html in there. Then you can disable the the bottom dock area for your toplevel QMainWindow and dock the left and right dock windows there. We do this trick with Linguist to get a very similar look, so you can check out Linguist http://doc.qt.io/qt-5/latest/linguist-manual.html to see how it works there.

The example below is a demonstration of how this can be done.

#include <QtGui>
 
class MainWindow : public QMainWindow
{
public:
 
  MainWindow(QWidget *parent = 0) : QMainWindow(parent)
  {
    QMainWindow *window = new QMainWindow(this);
    window->setCentralWidget(new QTextEdit(window));
    window->setWindowFlags(Qt::Widget);
    setCentralWidget(window);
 
    QDockWidget *dw = new QDockWidget(window);
    dw->setWidget(new QTextEdit(dw));
    window->addDockWidget(Qt::BottomDockWidgetArea, dw);
 
    QDockWidget *dockMain = new QDockWidget(this);
    dockMain->setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea );
    addDockWidget(Qt::LeftDockWidgetArea, dockMain);
    addDockWidget(Qt::RightDockWidgetArea, new QDockWidget(this));
    dockMain->setWidget(new QLabel("The left dock area", dockMain));
  }};
 
  int main(int argc, char **argv)
  {
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
  }

QScriptEngine::uncaughtExceptionNumber() is returning 0 even though the error is elsewhere. What's wrong?

The cause of the problem probably is QScriptValue::toString() http://doc.qt.io/qt-5/latest/qscriptvalue.html#toString is being called on the QScriptValue returned from the evaluate() http://doc.qt.io/qt-5/latest/qscriptengine.html#evaluate call before uncaughtExceptionNumber() is called. When QScriptValue::toString() http://doc.qt.io/qt-5/latest/qscriptvalue.html#toString is called it will reset the exception number in the QScriptEngine http://doc.qt.io/qt-5/latest/qscriptengine.html since it is ready for a new evaluate(). So code like:

   QScriptValue val = engine->evaluate(code);
   if (val.isError()) {
   qDebug() << val.toString();
   qDebug() << engine->uncaughtExceptionNumber();
}

Should be changed to:

QScriptValue val = engine->evaluate(code);
if (val.isError()) {
  qDebug() << engine->uncaughtExceptionNumber();
  qDebug() << val.toString();
}

So that the uncaughtExceptionNumber() is obtained before toString() is called.


I use a Qt-plugin in a non-Qt program on the Mac. When unloading the plugin, the application's menubar is deleted. What's going wrong ?

Unloading the plugin causes Qt to clear the menubar. You can disable Qt's interaction with the native menubar by calling qt_mac_set_native_menubar() http://doc.qt.io/qt-5/exportedfunctions.html#void-qt-mac-set-native-menubar-bool-enable

In general, most plugins in a non-Qt application don't need to interact with the menubar anyway.


Is Qt compatible with .NET?

Yes. You can use Qt to create .NET-compatible applications. For details on how to do this, please refer to Using Qt objects in Microsoft .NET in the documentation http://doc.qt.io/qt-5/activeqt.html.


Does Qt Creator support embedded/mobile software development?

Yes, Qt Creator can be used for developing for any platform that is supported by Qt.


Which image formats does Qt support?

Qt currently supports the following image file formats: PNG, BMP, XBM, XPM and PNM. It may also support JPEG and GIF, if specially configured during compilation. The different PNM formats are: PBM (P1 or P4), PGM (P2 or P5), and PPM (P3 or P6). In Qt 4.1 we will also support SVG which provides SVG 1.2 Tiny support.

Why does nothing happen when I set the palette background color on a QPushButton in some styles?

There are two different type of styles in Qt, one type just uses colors to indicate the background, foreground etc and the other type is a pixmap based one which usually rely on a theming engine on the underlying platform. When the style is a pixmap based one then simply changing the palette will usually not result in a visual change on that widget. Currently, there are three pixmap based styles, these being Windows XP, Windows Vista and Mac.

These styles use the platform's theming engine to draw most of the parts of the widgets. The engine uses pixmaps to define its look. Setting the color of a role in the Qt palette therefore will not always result in changes to the looks of the widget, since this new color will not change the pixmap defined in the theming engine. (Other things like font color of course will work as usual). See:

http://doc.qt.io/qt-5/qq/qq09-q-and-a.html#winxp

You have several options:

 1. **Go with the flow**

Just accept the style. Easy, and gives your UI a consistent look.

 2. **Set the style of that one widget to something like Windows Style**

Of course, that will make the widget look very different from all the others, since they won't have the same visual style (e.g. other types of borders etc).

 3. **Use QProxyStyle**

Check out http://doc.qt.io/qt-5/qproxystyle.html

 4. **Use Stylesheets instead**

Using stylesheets will enable you to change just part of the look and feel of a widget and still keep the native look and feel for other widgets. It will preserve what it can about the widget being styled and enable it to be changed easily.

See http://doc.qt.io/qt-5/stylesheet.html for more information


How can I change the size of the icon in the tab of a QToolBox?

The easiest way is probably by setting a stylesheet http://doc.qt.io/qt-5/latest/stylesheet.html on the QToolBox as follows:

toolbox.setStyleSheet("icon-size: aNumberpx");

You can also achieve it by subclassing the style and setting the value of pixelMetric() http://doc.qt.io/qt-5/latest/qstyle.html#pixelMetric to what you want when the metric is QStyle::PM_SmallIconSize and the widget inherits QToolBox. The example below illustrates both ways.

#include <QtGui>
 
class Style : public QWindowsStyle
{
public:
  Style()
  {}
 
  int pixelMetric ( PixelMetric metric, const QStyleOption * option = 0, const QWidget * widget = 0 ) const 
  {
    if (metric == QStyle::PM_SmallIconSize && widget->inherits("QToolBox")) {
      return 50;
                }
    return QWindowsStyle::pixelMetric(metric, option, widget);
  }
 
};
class ToolBox : public QToolBox
{
public:
  ToolBox()
  {
    QPixmap pix(50, 50);
    pix.fill(Qt::red);
 
    addItem(new QLineEdit(this), QIcon(pix), "QLineEdit");
    addItem(new QPushButton("Click me", this), "QPushButton");
  }
};
 
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    ToolBox box;
#if 0
  app.setStyle(new Style());
#else
  box.setStyleSheet("icon-size: 50px");
#endif
    box.show();
    return app.exec();    
}

Is there a way to tell QTreeView to always resize itself based on the contents of all columns?

To make a QTreeView always resize itself based on the contents of all columns, you can connect to the dataChanged() http://doc.qt.io/qt-5/latest/qabstractitemmodel.html#dataChanged signal and call resizeColumnToContents() http://doc.qt.io/qt-5/qtreeview.html#resizeColumnToContents when the data changes.

See the following example for an illustration:

#include <QtGui>
 
class TreeView :public QTreeView
{
    Q_OBJECT
public:
    TreeView();
public slots:
    void adaptColumns(const QModelIndex &topleft, 
                      const QModelIndex &bottomRight);
private:
    QStandardItemModel *model;
};
 
TreeView::TreeView() : QTreeView()
{
    // Create a generic model for storing custom data
    model = new QStandardItemModel();
    // Prepend 4 rows into the model
    model->insertRows(0, 4);
    // Prepend 4 columns into the model
    model->insertColumns(0, 4);
    for (int row = 0; row < 4; row++) {
        for (int col = 0; col < 4; col++) {
            // Return a model index for the given row and column.
            QModelIndex index = model->index(row, col);
            // Set the index's data to the specified value
            model->setData(index, QVariant((row+1) * (col+1)).toString());
        }
    }
    setModel(model);
    connect(model, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex& ) ), 
            this, SLOT(adaptColumns(const QModelIndex &, const QModelIndex&) ) );
}
 
void TreeView::adaptColumns (const QModelIndex & topleft, const QModelIndex& bottomRight)
{
    int firstColumn= topleft.column();
    int lastColumn = bottomRight.column();
    // Resize the column to the size of its contents
    do {
        resizeColumnToContents(firstColumn);
        firstColumn++;
    } while (firstColumn < lastColumn);
}
 
#include "main.moc"
 
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    TreeView view;
    view.show();
    return app.exec();
}

How can I make the scrollbar thinner ?

The scrollbar will not be thinner than the QApplication::globalStrut() http://doc.qt.io/qt-5/latest/qapplication.html#globalStrut-prop so you can use this to make sure it has a certain minimum size.

Another approach that also can make it thinner than the default is to subclass the style and reimplement pixelMetric() http://doc.qt.io/qt-5/latest/qstyle.html#pixelMetric

int pixelMetric(PixelMetric metric, const QWidget *widget = 0) const
{
  if (metric == QStyle::PM_ScrollBarExtent)
    return 5; // This will make the scrollbar five pixels wide
  return style->pixelMetric(metric, widget);
}

How can I detect a period of no user interaction?

What you will need to do is use a QTimer http://doc.qt.io/qt-5/latest/qtimer.html that times out after a number of minutes of no user interaction. Whenever there is user interaction, then you restart the timer. The easiest way to detect any user interaction within an application i.e. mouse clicks(any button), mouse wheel and keystrokes is to install an event filter on the application that listens for these kind of events. For example:

#include <QtGui>
 
class Widget : public QWidget
{
    Q_OBJECT
public:
    Widget()
    {
        timer = new QTimer(this);
        timer->start(4000);
        installEventFilter(this);
        connect(timer, SIGNAL(timeout()), this, SLOT(testSlot()));
    }
    bool eventFilter(QObject *o, QEvent *evt)
    {
        switch(evt->type()) {
        case QEvent::MouseButtonPress:
        case QEvent::MouseButtonRelease:
        case QEvent::Wheel:
        case QEvent::KeyPress:
        case QEvent::KeyRelease:
            timer->start(6000);
            break;
        default: 
            break;
        }
        return false;
    }
private:
    QTimer *timer;
 
public slots:
 
    void testSlot()
    {
        qDebug() << No user interaction;
    }
};
#include main.moc"
 
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    Widget box;
    box.resize(100, 200);
    box.show();
    return app.exec();    
}

How can I change the color of the items in my model?

In order to change the color of the items in the model you need to reimplement the data() http://doc.qt.io/qt-5/qabstractitemmodel.html#data function and return the colors you want for the Qt::BackgroundColorRole or the Qt::TextColorRole roles http://doc.qt.io/qt-5/qt.html#ItemDataRole-enum.

The example below illustrates how this can be achieved.

Note that you can also reimplement QStyledItemDelegate::paint() http://doc.qt.io/qt-5/latest/qstyleditemdelegate.html#paint in order to change the color the items in a view.

#include <QtGui>  
 
class ColorModel : public QAbstractTableModel
{ 
public:
    ColorModel(QObject *parent)  : QAbstractTableModel(parent)
    {         
        QStringList firstRow;
        QStringList secondRow;          
        for (int i = 0; i < 5; i++ ) {
            firstRow.insert(i,"Row " + QString::number(i+1));        
            secondRow.insert(i,"Row " + QString::number(i+1));         
        }         
        stringList << firstRow << secondRow;
    }      
 
    // Returns the number of rows     
    int rowCount(const QModelIndex &parent = QModelIndex()) const     
    {         
        return 2;     
    }      
 
    // Returns the number of columns      
    int columnCount(const QModelIndex &parent = QModelIndex()) const     
    {         
        return 5;     
    }      
 
    // Returns an appropriate value for the requested data.     
    // If the view requests an invalid index or if the role is not     
    // Qt::DisplayRole, Qt::BackgroundColorRole or QTextColorRole, an invalid variant is 
    // returned.
    // Any valid index that corresponds to a string for the index's column and row in     
    // the stringlist is returned for the Qt::DisplayRole      
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const      
    {
        if (!index.isValid())             
            return QVariant();          
        if (role == Qt::BackgroundRole) 
        {             
            if (index.row() == 0)                 
                return QColor(Qt::blue);             
            else                 
                return QColor(Qt::white);
        } else if (role == Qt::DisplayRole) {             
            QStringList list = (QStringList)stringList.at(index.row());             
            return list.at(index.column());         
        } else if (role == Qt::ForegroundRole ) {
            if (index.row() == 1)                 
                return QColor(Qt::red);
        }
        return QVariant();     
    }  
 
private:      
    // Each row will consist of a list of strings     
    QList<QStringList>stringList;
};  
 
int main(int argc, char **argv)
{     
    QApplication app(argc, argv);     
    QWidget widget;      
    QHBoxLayout *layout = new QHBoxLayout(&widget);     
    QTreeView *treeView = new QTreeView(&widget);     
    QTableView *tableView = new QTableView(&widget);
    ColorModel *model = new ColorModel(tableView);     
    tableView->setModel(model);
    treeView->setModel(model);     
    layout->addWidget(treeView);
    layout->addWidget(tableView);     
    widget.show();     
    return app.exec();  
}

How can I handle events in the titlebar and change its color etc ?

The titlebar belongs to the OS and we don't have control over that one. You can create your own titlebar, but note that this requires some work. In order to create your own titlebar then make a QWidget http://doc.qt.io/qt-5/latest/qwidget.html subclass that contains three toolbuttons that handle the close, minimize and maximize events in addition to the moving of the window.

Then make a QFrame http://doc.qt.io/qt-5/latest/qframe.html subclass which does not have a titlebar provided via the window system. This is done by setting the Qt::FramelessWindowHint http://doc.qt.io/qt-5/latest/qt.html#WindowType-enum window flag, however this will make it impossible to resize or move the window via the window system. What can be done is you can add your custom titlbar as a private member to the frame and add the it first to the frame's vertical layout. The frame also needs a content widget which allows widgets to be added to it. Finally the QFrame subclass needs to reimplement the mouse events to handle the resizing and moving of the window.

The example below demonstrates how this can be achieved.

#include <QtGui>
 
class TitleBar : public QWidget
{
    Q_OBJECT
public:
    TitleBar(QWidget *parent)
    {
        // Don't let this widget inherit the parent's backround color
        setAutoFillBackground(true);
        // Use a brush with a Highlight color role to render the background 
        setBackgroundRole(QPalette::Highlight);
 
        minimize = new QToolButton(this);
        maximize = new QToolButton(this);
        close= new QToolButton(this);
 
        // Use the style to set the button pixmaps
        QPixmap pix = style()->standardPixmap(QStyle::SP_TitleBarCloseButton);
        close->setIcon(pix);
 
        maxPix = style()->standardPixmap(QStyle::SP_TitleBarMaxButton);
        maximize->setIcon(maxPix);
 
        pix = style()->standardPixmap(QStyle::SP_TitleBarMinButton);
        minimize->setIcon(pix);
 
        restorePix = style()->standardPixmap(QStyle::SP_TitleBarNormalButton);
 
        minimize->setMinimumHeight(20);
        close->setMinimumHeight(20);
        maximize->setMinimumHeight(20);
 
 
        QLabel *label = new QLabel(this);
        label->setText("Window Title");
        parent->setWindowTitle("Window Title");
 
        QHBoxLayout *hbox = new QHBoxLayout(this);
 
        hbox->addWidget(label);
        hbox->addWidget(minimize);
        hbox->addWidget(maximize);
        hbox->addWidget(close);
 
        hbox->insertStretch(1, 500);
        hbox->setSpacing(0);
        setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
 
        maxNormal = false;
 
        connect(close, SIGNAL( clicked() ), parent, SLOT(close() ) );
        connect(minimize, SIGNAL( clicked() ), this, SLOT(showSmall() ) );
        connect(maximize, SIGNAL( clicked() ), this, SLOT(showMaxRestore() ) );
    }
 
public slots:
    void showSmall()
    {
        parentWidget()->showMinimized();
    }
 
    void showMaxRestore()
    {
        if (maxNormal) {
            parentWidget()->showNormal();
            maxNormal = !maxNormal;
            maximize->setIcon(maxPix);
        } else {
            parentWidget()->showMaximized();
            maxNormal = !maxNormal;
            maximize->setIcon(restorePix);
        }
    }
protected:
    void mousePressEvent(QMouseEvent *me)
    {
        startPos = me->globalPos();
        clickPos = mapToParent(me->pos());
    }
    void mouseMoveEvent(QMouseEvent *me)
    {
        if (maxNormal)
            return;
        parentWidget()->move(me->globalPos() - clickPos);
    }
 
private:
    QToolButton *minimize;
    QToolButton *maximize;
    QToolButton *close;
    QPixmap restorePix, maxPix;
    bool maxNormal;
    QPoint startPos;
    QPoint clickPos;
};
 
class Frame : public QFrame
{
public:
 
    Frame()
    {
        m_mouse_down = false;
        setFrameShape(Panel);
 
        // Make this a borderless window which can't
        // be resized or moved via the window system
        setWindowFlags(Qt::FramelessWindowHint);
        setMouseTracking(true);
 
        m_titleBar = new TitleBar(this);
 
        m_content = new QWidget(this);
 
        QVBoxLayout *vbox = new QVBoxLayout(this);
        vbox->addWidget(m_titleBar);
        vbox->setMargin(0);
        vbox->setSpacing(0);
 
        QVBoxLayout *layout = new QVBoxLayout(this);
        layout->addWidget(m_content);
        layout->setMargin(5);
        layout->setSpacing(0);
        vbox->addLayout(layout);
    }
 
    // Allows you to access the content area of the frame
    // where widgets and layouts can be added
    QWidget *contentWidget() const { return m_content; }
 
    TitleBar *titleBar() const { return m_titleBar; }
 
    void mousePressEvent(QMouseEvent *e)
    {
        m_old_pos = e->pos();
        m_mouse_down = e->button() == Qt::LeftButton;
    }
 
    void mouseMoveEvent(QMouseEvent *e)
    {
        int x = e->x();
        int y = e->y();
 
        if (m_mouse_down) {
            int dx = x - m_old_pos.x();
            int dy = y - m_old_pos.y();
 
            QRect g = geometry();
 
            if (left)
                g.setLeft(g.left() + dx);
            if (right)
                g.setRight(g.right() + dx);
            if (bottom)
                g.setBottom(g.bottom() + dy);
 
            setGeometry(g);
 
            m_old_pos = QPoint(!left ? e->x() : m_old_pos.x(), e->y());
        } else {
            QRect r = rect();
            left = qAbs(x - r.left()) <= 5;
            right = qAbs(x - r.right()) <= 5;
            bottom = qAbs(y - r.bottom()) <= 5;
            bool hor = left | right;
 
            if (hor && bottom) {
                if (left)
                    setCursor(Qt::SizeBDiagCursor);
                else 
                    setCursor(Qt::SizeFDiagCursor);
            } else if (hor) {
                setCursor(Qt::SizeHorCursor);
            } else if (bottom) {
                setCursor(Qt::SizeVerCursor);
            } else {
                setCursor(Qt::ArrowCursor);
            }
        }
    }
 
    void mouseReleaseEvent(QMouseEvent *e)
    {
        m_mouse_down = false;
    }
 
private:
    TitleBar *m_titleBar;
    QWidget *m_content;
    QPoint m_old_pos;
    bool m_mouse_down;
    bool left, right, bottom;
};
 
 
#include "main.moc"
 
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
 
    Frame box;
    box.move(0,0);
 
    QVBoxLayout *l = new QVBoxLayout(box.contentWidget());
    l->setMargin(0);
    QTextEdit *edit = new QTextEdit(box.contentWidget());
    l->addWidget(edit);
 
    box.show();
    return app.exec();    
}

Note that some strange behavior may be seen when resizing the window really small horizonally to the right on Windows (the window will start moving instead of resizing). This is due to limitations on Windows and there is nothing we can do about this unfortunately.


How can I specify a default location and file name that will be used if a user selects print to file, but not have print to file as the default option ?

When calling setOutputFileName() http://doc.qt.io/qt-5/latest/qprinter.html#setOutputFileName you can specify the default output directory for the file, but this will also cause QPrinter http://doc.qt.io/qt-5/latest/qprinter.html to print to the file specified. If you want to specify an output directory for the file and at the same time have printing to a real printer as the default option, then this is possible to achieve. To do so you need to create a QPrintDialog http://doc.qt.io/qt-5/latest/qprintdialog.html and if the user choose print to file the print dialog will set the output file name to a non-empty string. The programmer can then choose to look at the file name after the print dialog has been executed and pop up a filedialog or similar to specify the full path for the name.


Why are the changes made in the Language tab in the International settings not respected on the Mac?

At the moment it is not possible to detect what language is set in the International->Language tab using QLocale http://doc.qt.io/qt-5/latest/qlocale.html. This has however been fixed for Qt 4.8, see this entry http://bugreports.qt.io/browse/QTBUG-190 in the Bug Tracker for more information.

In Qt 4.7 and below you can figure out the preferred language using QSettings http://doc.qt.io/qt-5/latest/qsettings.html. See the following example:

QSettings settings("apple.com");  
QStringList sl = settings.value("AppleLanguages").toStringList();  
qDebug() << "Lang is " << sl.first();


How can I prevent the view from scrolling when the user selects an item in a view?

In order to only allow scrolling when the user drags the scrollbar, you can reimplement scrollTo() http://doc.qt.io/qt-5/qabstractitemview.html#scrollTo to do nothing.

See the following example for a demonstration:

#include <QtGui>  
 
class TableWidget : public QTableWidget
{ 
public:
    TableWidget()
    {              
        setColumnCount(15);       
        setRowCount(20);
        QTimer::singleShot(3000, this, SLOT(testScroll()));
    }    
 
    void scrollTo (const QModelIndex &index, ScrollHint hint = EnsureVisible)    
    {  } 
};  
 
int main(int argc, char **argv) 
{     
    QApplication app(argc, argv);
    TableWidget table;     
    table.show();     
    return app.exec(); 
}

I am experiencing random crashes when running my application on Windows, what can be wrong?

This sounds like potential memory corruption. which in turn could be caused by conflicting runtime libraries. Make sure you don't have a mismatch of runtime libraries - if you have built Qt in release mode and your application in debug mode this means that it will be using two different runtime libraries. A release C runtime for Qt and a debug C runtime for your application. This means that there are two heaps in use and as a result if objects get passed from one heap to another (i.e. from Qt to the application and vice versa) then memory corruption will occur. You can usually catch this at build time, if you see a link warning about default libraries then this is usually indicative of this problem. The only way to resolve it is to ensure that Qt and your application is built in the same mode.


How to prevent right mouse click selection for a QTreeWidget?

In order to prevent selection of an item when right clicking, you can reimplement QTreeWidget::mousePressEvent() http://doc.qt.io/qt-5/latest/qtreeview.html#mousePressEvent to do nothing if it is the right mouse button which is being clicked. The example below illustrates how this can be done.

#include <QtGui>
 
class TreeWidget : public QTreeWidget
{
public:
	TreeWidget()
	{
		setColumnCount(1);
		QList<QTreeWidgetItem *> items;
		for (int i = 0; i < 10; ++i)
			items.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList(QString(item: %1).arg(i))));
		insertTopLevelItems(0, items);
	}
	void mousePressEvent(QMouseEvent *event)
	{
		if (event->button()== Qt::RightButton)
			return;
		else
			QTreeWidget::mousePressEvent(event);
	}
 
	void contextMenuEvent(QContextMenuEvent *event)
	{
		QMenu *menu = new QMenu(this);
		menu->addAction(first);
		menu->addAction(second);
		menu->addAction(third);
		menu->exec(QCursor::pos());
	}
};
int main(int argc, char **argv)
{
	QApplication app(argc, argv);
	TreeWidget box;
	box.show();
	return app.exec();
}


My application's plugins won't load on some Windows machines, what can be wrong ?

If you are using Visual Studio 2005 and are using Service Pack 1 then make sure your plugin, your application and Qt is built using the Service Pack as your distributed application will not run otherwise.

Also, when using Visual Studio 2005, make sure you copy the manifest file created when linking the application into the same folder as the application executable.

http://doc.qt.io/qt-5/deployment-windows.html#visual-studio-2005

You also need to include the run time libraries by installing them on the end-user's system.

Also, if you are deploying plugins that depend on a client library, you need to deploy the client library if it does not exist on the target machine. So, if you for example are deploying a mysql plugin, then you need to distribute libmySQL.dll if it does not exist on the target machine.

Also, note that the plugin needs to be located in a subdirectory named according to the type of plugin it is in order for Qt to find it automatically. So if you are using the jpeg plugin for example, the plugin needs to be located in a subdirectory named imageformats within your distribution directory. If you are using a sql driver plugin, it needs to be in a subdirectory called sqldrivers and so on.

See the general documentation on deployment for more details about this:

http://doc.qt.io/qt-5/deployment-windows.html


Is it possible to suppress the scaling of the background of QGraphicsView?

If you use setBackgroundBrush() http://doc.qt.io/qt-5/qgraphicsscene.html#backgroundBrush-prop instead of drawBackground() http://doc.qt.io/qt-5/latest/qgraphicsscene.html#drawBackground on the QGraphicsScene http://doc.qt.io/qt-5/latest/qgraphicsscene.html, you get a static background that does not scale or transform. QBrush http://doc.qt.io/qt-5/latest/qbrush.html can take a QImage http://doc.qt.io/qt-5/latest/qimage.html, QPixmap http://doc.qt.io/qt-5/latest/qpixmap.html, a solid color, different gradients and different patterns.


How can I add version information to my application?

You can use the qmake variable VERSION to add version information to your library or application. See the documentation on the qmake VERSION variable http://doc.qt.io/qt-5/4.7/qmake-variable-reference.html#qt-version

When creating a .dll with a version number embedded then this is done by setting

VERSION = x.y.z.

in the .pro file. This will also cause the major version number to automatically be placed in the target filename. For example, when setting

VERSION = 2.0.5
TARGET = mylib

the output file is called mylib2.dll.

In order to remove the version number from the target name, then you can use the TARGET_EXT http://doc.qt.io/qt-5/qmake-variable-reference.html#target-ext variable. For instance, setting the output filename without the major version number on Windows can be done by setting it like this:

TARGET_EXT = .dll

On Windows, you can alternatively create a resource file http://doc.qt.io/qt-5/qmake-variable-reference.html#rc-file and specify this as part of your application using:

RC_FILE = foo.rc

Note that the version information will not be part of the target filename.



OpenGL and translucent background do not work together due to a limitation

Due to a limitation in window managers, it is not possible to combine OpenGL with a translucent background window (set with WA_TranslucentBackground). The reason for this is because OpenGL is rendered directly onto the screen and the compositor used to enable the translucent background cannot ensure that the OpenGL is rendered correctly.

There is nothing that can be done in Qt to fix this as it needs to be done on the side of the window manager.

To work around this issue you can either just use Qt to render everything and not OpenGL, or you can render the OpenGL into a pixmap and draw that onto your widget instead.


The eclipse integration will not install when using Wascana Desktop Developer, what can be wrong?

When installing the Wascana Desktop Developer the resulting executable for Eclipse is called Wascana.exe. The eclipse integration expects the eclipse.exe filename and cannot find the correct executable. To work around this you can add a dummy file called eclipse.exe to the eclipse directory.


I get errors when building my Qt/Windows project where one of my paths appears to be cut off, what can be wrong?

If the link error is related to part of your path where you have a space in its name then you need to move your application to a directory without spaces as nmake is not able to understand paths with spaces in them. If you have installed Qt into a directory with spaces in it then Qt needs to be reinstalled into a path without spaces.


How can I clone a widget?

Qt has no automated way of copying a widget and its properties. You have two options for achieving this though:

1) If you create the widget and its children as a form (in designer) you can easily recreate it using QUiLoader.

2) You can create a method that asks the control what class it is and then makes a new one. Then the function needs to copy the attributes across and then recurse down the widget tree.


What does the syntax CONFIG(debug,debug|release) mean ? What does the 1st argument specify and similarly what is the 2nd ?

When qmake http://doc.qt.io/qt-5/latest/qmake-manual.html processes a pro file it could process it up to three times depending on what the configuration is set to. Usually it will do it three times. Once for debug, once for release and one final one for debug_and_release. This is so that both configurations can be generated for at the same time. Therefore when it is required to have debug/release specific settings in a pro file then there is a need to check if qmake is processing the pro file with a particular configuration in mind. As debug and release might be in CONFIG at the same time a check for just debug or release is likely to always be true (particularly if you have debug_and_release enabled). So, this construct

CONFIG(debug, debug|release) {
    HEADERS += debug.h
    SOURCES += debug.c
}

checks for when the debug configuration is being processed comparing where debug and release are mutually exclusive. As CONFIGs are order dependent (ie the last one set will be considered the active config for mutual exclusive sets like debug and release) a second parameter can be used to specify a set of values to consider, for example:

        CONFIG = debug
        CONFIG += release
        CONFIG(release, debug|release):message(Release build!)#will be displayed
        CONFIG(debug, debug|release):message(Debug build!) #not displayed

Note that you should use the build_pass http://doc.qt.io/qt-5/latest/qmake-function-reference.html variable to filter out messages, otherwise you will get messages when it creates the Makefile which will be the configuration specific makefile. When adding the build_pass variable in conjunction with the following scope

build_pass:CONFIG(debug, debug|release) {
message(Debug bulid)
}
else:build_pass {
message(Release build)
}

the output will be as follows:

Project MESSAGE: Debug build Project MESSAGE: Release build


How can I add a non-resource image to a QTextDocument?

You can add a non-resource image to a QTextDocument http://doc.qt.io/qt-5/latest/qtextdocument.html by using the internal class QTextObjectInterface http://doc.qt.io/qt-5/qtextobjectinterface.html for inserting custom objects into a QTextDocument.

The subclass of QTextObjectInterface will result in a handler for the object you would want to draw. Information like the name of the pixmap or geometry information is stored in the QTextFormat http://doc.qt.io/qt-5/qtextformat.html that you specify at QTextCursor::insertText() http://doc.qt.io/qt-5/4.7/qtextcursor.html#insertText time and that are used as arguments to the functions of QTextObjectInterface. See the documentation:

http://doc.qt.io/qt-5/qabstracttextdocumentlayout.html#registerHandler http://doc.qt.io/qt-5/qchar.html#SpecialCharacter-enum http://doc.qt.io/qt-5/qtextformat.html#ObjectTypes-enum

See the following example for an illustration:

#include <QtGui>  
 
class MyHandler : public QObject, public QTextObjectInterface
{  
    Q_OBJECT   
    Q_INTERFACES(QTextObjectInterface) 
public:
    MyHandler(QObject* par = 0) : QObject(par), px("polygon.png")  {}  
    QSizeF intrinsicSize(QTextDocument *doc, int posInDoc, const QTextFormat &fmt)  
    {
        Q_UNUSED(doc)    
        Q_UNUSED(posInDoc)    
        Q_UNUSED(fmt)     
        return QSizeF(px.size() );  
    }  
 
    void drawObject(QPainter* p, const QRectF &rect, QTextDocument *doc, 
                    int posInDoc, const QTextFormat &fmt)  
    {   
        Q_UNUSED(doc)
        Q_UNUSED(posInDoc)    
        Q_UNUSED(fmt)    
        p->drawPixmap(rect.toRect(), px );  
    }
 
private:  
    QPixmap px; 
};  
 
class Widget : public QTextEdit
{ 
public:
    Widget(QWidget* parent = 0) : QTextEdit(parent)  
    {   
        MyHandler* handler = new MyHandler(this);
        document()->documentLayout()->registerHandler(QTextCharFormat::UserObject, 
                                                      handler);    
        QTextCharFormat fmt;
        fmt.setObjectType(QTextCharFormat::UserObject);
        textCursor().insertText("hello");
        textCursor().insertText(QString(QChar::ObjectReplacementCharacter), fmt);
        textCursor().insertText("world");  
    } 
};  
 
#include "main.moc"  
 
int main(int argc, char **argv) 
{  
    QApplication a(argc, argv);  
    Widget w;  
    w.show();
    return a.exec(); 
}

How can I modify the color for individual words for items in a view?

In order to change the color for only some of the words or characters in an item, you need to draw the item yourself. This can be done by subclassing QStyledItemDelegate http://doc.qt.io/qt-5/latest/qstyleditemdelegate.html and reimplementing paint() http://doc.qt.io/qt-5/qitemdelegate.html#paint to draw the text using QPainter::drawText() http://doc.qt.io/qt-5/qpainter.html#drawText-9.

The example below demonstrates how this can be done:

#include <QtGui>  
 
class ItemDelegate: public QItemDelegate
{ 
public:
    ItemDelegate() {}      
    void paint(QPainter *painter, const QStyleOptionViewItem &option, 
               const QModelIndex &index) const       
    {         
        if(index.row() == 0 ) {             
            QRect r;
            painter->drawText(option.rect,Qt::TextSingleLine, "Item ", &r);             
            painter->setPen(Qt::red);             
            QRect modOptRect = option.rect;             
            modOptRect.setLeft(option.rect.left() + r.width());
            painter->drawText(modOptRect, "1");
        } else {
            QItemDelegate::paint(painter, option, index);         
        }     
    } 
};  
 
int main(int argc, char** argv) 
{     
    QApplication app(argc, argv);     
    QTreeWidget tree;
    tree.setItemDelegate(new ItemDelegate);     
    QTreeWidgetItem *item1= new QTreeWidgetItem();     
    QTreeWidgetItem *item2= new QTreeWidgetItem();
    item2->setText(0, "item 2");     
    tree.addTopLevelItem(item1);
    tree.addTopLevelItem(item2);     
    tree.show();     
    return app.exec(); 
}

What kind of font support does Qt for Embedded Linux offer?

Qt for Embedded Linux has support for TrueType, Postscrip Type1, Windows font files, and BDF fonts, both anti-aliased and conventional. The fonts can be pre-rendered for CPU and storage savings. The fonts are shared between applications. New font engines can easily be added.


Does Qt for Embedded Linux offer support for internationalization?

Yes.Qt for Embedded Linux incorporates all the Qt 4 features that greatly simplify the internationalization process, including: language and font-aware layout, extensive Unicode support, bi-directional language support, and mixed international text all in one document.


Is a GUI software design tool provided with Qt for Embedded Linux?

Yes. Qt for Embedded Linux includes Qt Designer http://doc.qt.io/qt-5/latest/designer-manual.html, the powerful GUI layout and forms builder. Designer files can be generated on Windows, x11 (or Mac) platforms and still be used in Qt for Embedded Linux programs.


What is the difference between Qt for Embedded Linux and Qt/X11?

Qt/X11 is built on top of the x11 window system, but Qt for Embedded Linux provides its own window system and has therefore lower RAM and ROM requirements. With Qt for Embedded Linux, applications will access the display directly for optimal graphics performance. Nonetheless, the API for developing applications is the same for Qt/X11 and Qt for Embedded Linux.


Can Qt for Embedded Linux display on landscape displays in portrait orientation and visa versa?

Yes. Qt for Embedded Linux supports 90, 180 and 270 degree rotation. It is simple to add additional transformations if needed.


Does Qt for Embedded Linux support any screen size?

Yes. Qt for Embedded Linux handles screen sizes from very small to very large screens such as 4000x4000 pixels.


How do I run Qt for Embedded Linux applications without a keyboard?

Run the application with the -nokeyboard option.


In Qt for Embedded Linux, when I create a pen with the style Qt::DashLine and a width of greater than 1, it does not appear to work in QPainter::drawLine(). Is that a limitation of the embedded library?

This is the expected behaviour, caused by the internal structure of the embedded paint engine which is not as complete as that of other platforms.


What kind of IDEs can be used with Qt for Embedded Linux?

Qt for Embedded Linux applications can be developed in full-fledged IDEs such as Qt Creator, Eclipse, KDevelop or other X11 IDEs. Both Eclipse and KDevelop support auto-completion of code and debugging. Most of Qt for Embedded Linux application development can also be done on Windows using Visual studio.


Does the Qt for Embedded Linux graphics subsystem have the capability write the updates only to the frame buffer, or does it always update the complete frame buffer?

Qt for Embedded Linux automatically updates only what has changed, **not** the complete frame.


How do I enable the touch screen in Qt for Embedded Linux?

Qt for Embedded Linux supports touch panels, but you may need to write your own driver.

Qt provides support for Linux Touch Panel and the driver is implemented in the file:

  • QTDIR/src/gui/embedded/qmouselinuxtp_qws.cpp*

Additionally Qt for Embedded Linux has support for tslib which indicates that any touch screen supported by tslib can be used in Qt.


Can I execute a Qt for Embedded Linux application on my development PC although my X-server is running?

Yes, by using the Qt Virtual Framebuffer (QVFb).


Why do I receive the following error message when building makeqpf: Some of the required modules (nocrosscompiler) are not available.

To solve this problem do the following:

  1. Configure and compile Qt for Embedded Linux for the system on which you are compiling (do not cross-compile).
  2. compile makeqpf.

This does not mean that you cannot cross-compile Qt for Embedded Linux. Copy the Qt for Embedded Linux directory, and let one be compiled for your local system and another one for your target system.


Can I develop software with Qt/X11 or Qt/Windows and easily change to Qt for Embedded Linux?

Yes. Qt for Embedded Linux is source code compatible with the desktop versions of Qt 4.x, so any program working with Qt 4.x will work with Qt for Embedded Linux (as long as it does not contain platform-dependent code, of course).


Is an X server required for Qt for Embedded Linux?

No. Qt for Embedded Linux always runs without an X server. Any Qt for Embedded Linux application can function as the master process, which is not a graphics server like X11 that handles device input and window allocation.


What is a standard way of configuring Qt/e for a desktop system used for developing Qt for Embedded Linux applications?

To configure Qt for Embedded Linux as a shared library on an X86 platform with:

  • QVFb support
  • debug symbols
  • support for 8, 16 and 32 bit depth
  • thread support

use the following command:

./configure -qvfb -embedded x86 -debug -depths 8,16,32 -thread -shared.


What are the graphics capabilities of Qt for Embedded Linux?

Qt for Embedded Linux's graphics subsystem provides everything needed to create state-of-the-art user interfaces, including:

  • support for semi-transparency (alpha-blending) and anti-aliasing
  • optional floating-point coordinate system
  • painter paths
  • gradients
  • support for interchangeable underlying paint engines and off-screen rendering.
  • Qt for Embedded Linux integrates SVG 1.1/1.2 Tiny drawings and animations, and additional features for developers using OpenGL.


How do I add true-type fonts when migrating my application from Qt-X11 to Qt for Embedded Linux?

You must copy them to QTDIR/lib/fonts, and specify them in the file QTDIR/lib/fonts/fontdir.

For further information see: http://doc.qt.io/qt-5/qt-embedded-fonts.html


Why do I receive the QVFb Driver Not Found message when running a Qt for Embedded Linux application?

If you receive the message QVFb: Driver Not Found when running a Qt for Embedded Linux application with the options: -qws -display , the problem is that QVFb has not started.

To solve the problem, start QVFb before you start the application.


Why does the compilation of Qt for Embedded Linux fail with the message: dialogs/qprintdialog.cpp:790: cups/cups.h: No such file or directory?

You are missing the cups development package. Install the package and the problem should be solved. If you do not need cups, you can configure Qt with the option -no-cups.


Is there a way to get access to the virtual framebuffer inside a QPixmap, so that we can render to this address, and then blt the result to screen?

Yes. It is Qt for Embedded Linux specific, but you can obtain a pointer to the bits of a QPixmap http://doc.qt.io/qt-5/qpixmap.html. For example:

void SomeClass::someFunc(){
#ifdef Q_WS_QWS
  QPixmap pm;
  uchar *bits = pm.scanLine(0);
  int bytesPerLine = pm.bytesPerLine();
#endif

}


How can I add an accelerated graphics driver?

Qt for Embedded Linux has the capacity to make use of hardware accelerators. To do so for a PCI or an AGP driver, you need to perform the steps outlined in this document http://doc.qt.io/qt-5/qt-embedded-accel.html.


Why is it not allowed to copy QObjects?

The reason it is not possible to copy QObjects http://doc.qt.io/qt-5/latest/qobject.html is that QObject is a polymorphic object, and that polymorphic objects cannot be copied.

QPushButton pushButton;
QObject object = pushButton;
Q_ASSERT(object.metaObject() == &QPushButton::staticMetaObject)

This would assert, and all calls of virtual functions would call QObject's implementation.


Are there any tools for the job of converting Windows MFC dialogs?="Yes, the GUI layout of Windows dialogs can to some degree be automatically translated to the Qt equivalent using KDAB's tool KNUT() http://www.klaralvdalens-datakonsult.se/?page=products&sub

knut



Is it possible to set a header and footer when printing a QTextDocument?

There is no API for this at the moment, so you will have to implement this yourself. In order to do this manually, what needs to be done is to print the header and footer yourself and use QTextDocument::drawContents() http://doc.qt.io/qt-5/qtextdocument.html#drawContents to draw the relevant part of the page that will fit on the paper. In order to do this you need to calculate what area of the page rectangle your header and footer will occupy and the rest is used for the content of the document. By moving the rectangle that gets what needs to be painted each time and translating the painter so that is effectively painting at 0x0 then it will paint the contents for that page as drawContents() http://doc.qt.io/qt-5/qtextdocument.html#drawContents will clip the painting to the specified rectangle. This is put into a while loop that checks that the rectangle to be painted is actually intersecting with the complete contents rectangle.

The following is an example of how it can be implemented:

#include <QtGui>
 
int main(int argc, char **argv)
{
    QApplication a(argc, argv);
    QFile f("test.html");
    f.open(QIODevice::ReadOnly);
    QString content = f.readAll();
    f.close();
    QTextDocument td;
    td.setHtml(content);
    QPrinter p;
    QPrintDialog pd(&p, 0);
    pd.exec();
    td.setPageSize(p.pageRect().size());
    QRect innerRect = p.pageRect();
    innerRect.setTop(innerRect.top() + 20);
    innerRect.setBottom(innerRect.bottom() - 30);
    QRect contentRect = QRect(QPoint(0,0), td.size().toSize());
    QRect currentRect = QRect(QPoint(0,0), innerRect.size());
    QPainter painter(&p);
    int count = 0;
    painter.save();
    painter.translate(0, 30);
    while (currentRect.intersects(contentRect)) {
        td.drawContents(&painter, currentRect);
        count++;
        currentRect.translate(0, currentRect.height());
        painter.restore();
        painter.drawText(10, 10, QString("Header %1").arg(count));
        painter.drawText(10, p.pageRect().bottom() - 10, QString("Footer %1").arg(count));
        painter.save();
        painter.translate(0, -currentRect.height() * count + 30);
        if (currentRect.intersects(contentRect))
            p.newPage();
    }
    painter.restore();
    painter.end();
    return 0;
}

How do I run a Qt for Embedded Linux application without a mouse?

Run your embedded application with the option: -nomouse , this disables the mouse.


Can I use Qt for Embedded Linux on a PXA27x development board with our own version of Linux?

We have several customers successfully using PXA 255 board, and PXA 27x boards. Qt for Embedded Linux should work on any standard Linux which has support for the Linux frame buffer. If there is no Linux frame buffer support (which is very unlikely), it may be necessary to may adapt one of the graphics drivers to your graphics hardware. Qt for Embedded Linux has a specific plug-in API for adding your own graphics driver.


My Qt/Windows application is running out of user handles, as the application contains a huge amount of widgets. What can be done about this ?

In Qt versions below Qt 4.4, Qt will store a user handle for every widget in the application, including child widgets. This means that for every font, widget and so on, a user handle will be created and taking up memory. So having a huge amount of widgets can cause you to run into the user handles limit of windows. To solve this problem you should delete your widgets when they are being closed and recreate them when needed. Alternatively, you can paint your widgets instead of creating widgets, which is much more light weight.

Starting with Qt 4.4 we are using Alien which will give your application handle-less child widgets, causing it to be much more light-weight and resource friendly as we don't allocate user handles for every single widget. We only allocate user handles for top level widgets. See:


http://labs.trolltech.com/blogs/2007/08/09/qt-invaded-by-aliens-the-end-of-all-flicker


Parentheses show up incorrectly for English text in a right-to-left application. What is wrong?

In -reverse mode or when calling

setLayoutDirection(Qt::RightToLeft)

the default text direction is RightToLeft http://doc.qt.io/qt-5/latest/qt.html#LayoutDirection-enum. The display is how the Bidirectional Algorithm http://unicode.org/reports/tr9 defines the output should look.

Using -reverse together with English text will result in some artifacts like this. It's the task of the translator to ensure things look correct in a right to left language. He can do that by adding some special Unicode characters to the translated string (left-to-right marks etc). In Linguist http://doc.qt.io/qt-5/latest/linguist-manual.html, this can be done by right clicking in the translation field and selecting Insert Unicode control character/LRM Left-to-Right mark.




Is there a way to modify the window flags without causing flicker?

It is not possible to make changes to the window flags once the window has been created without causing flicker. Flicker is unavoidable since the window needs to be recreated.


How can I change the width of the scrollbar of QWebView?

The stylesheet API does not yet support styling QWebView http://doc.qt.io/qt-5/latest/qwebview.html, but you can style the webview's scrollbar using the style API.

You can subclass your style (or create a proxy style) and reimplement QStyle::pixelMetric() http://doc.qt.io/qt-5/latest/qstyle.html#pixelMetric to return the width you want when the metric is QStyle::PM_ScrollBarExtent http://doc.qt.io/qt-5/latest/qstyle.html#PixelMetric-enum. QWebView does not actually use a QScrollBar http://doc.qt.io/qt-5/latest/qscrollbar.html, so you need to be a bit sneaky here to get this to work. When QStyle::pixelMetric() is called in this case, the QWidget* http://doc.qt.io/qt-5/latest/qwidget.html passed in is 0 whereas it is the scrollbar in other cases. So you could set the style on the application and check if the widget is 0 in QStyle::pixelMetric(). If it is, you can assume it's the webview asking for it and therefore returning your modified size and if not fall back to the base class.

The example below demonstrates how this can be done:

#include <QtGui>
#include <QWebView>
 
class Style : public QWindowsStyle
{
public:
  Style()
  {
  }
  int pixelMetric ( PixelMetric metric, const QStyleOption * option = 0, const QWidget * widget = 0 ) const
  {
    if (metric == QStyle::PM_ScrollBarExtent && widget == 0)
      return 30;
    return QWindowsStyle::pixelMetric(metric, option, widget);
  }
 
};
class WebView : public QWebView
{
public:
  WebView()
  {
    qApp->setStyle(new Style());
    load(QUrl("http://doc.qt.io/qt-5/4.5/qwebview.html"));
    QTimer::singleShot(5000, this, SLOT(testSlot()));
  }
 
};
 
int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  WebView view;
  view.show();
  return app.exec();
}

I get an 'Error while parsing /XXX/qrc_XXX.cpp, Java Heap Space'. What's the problem ?

You need to increase the maximal amount of memory usable by Eclipse. In order to do so start Eclipse from the command line, with e.g.:

                 eclipse -vmargs -Xmx1000M
 

Is there a way of sizing the window so that it is never overlapped by the taskbar (or it doesn't overlap the taskbar)?

What you can do is call QDesktopWidget::availableGeometry() http://doc.qt.io/qt-5/qdesktopwidget.html#availableGeometry to determine what part of the desktop can be used.

The returned rect excludes the taskbar, so as long as you use only that geometry, you can be sure that your window won't be underneath or on top of the taskbar.


How can I draw shadows behind windows ?

This functionality is not supported in the Qt API yet and would therefore have to be done using native system calls. The function you are looking for in the Win32 API is called UpdateLayeredWindow() http://msdn2.microsoft.com/en-us/library/ms633556.aspx.

It requires that you first create a layered window as mentioned in the above documentation. Something similar can be achieved on X11 using an ARGB visual.We have an example of this in our Graphics Dojo http://labs.trolltech.com/page/Graphics/Examples/Examples1.

We plan on implementing support for this in the future:

http://bugreports.qt.io/browse/QTBUG-668

There are other solutions you can use for faking this effect for windows of a static size (useful for splash screens). For instance, you can take a screenshot of the desktop widget using the following code snippet:

    QSize SIZE(600, 300);  
QRect splashScreenRect(r.width() / 2 - SIZE.width() / 2, r.height() / 2 - SIZE.height() / 2, SIZE.width(), SIZE.height());  
QPixmap desktopBg = QPixmap::grabWindow(QApplication::desktop()->winId(), splashScreenRect.x(), splashScreenRect.y(), splashScreenRect.width(), splashScreenRect.height());

Then you would just draw this pixmap as normal and paint using alpha blending on top of it.


How can I display vertical text in the section of a QHeaderView?

The way to do this is to subclass QProxyStyle http://doc.qt.io/qt-5/latest/qproxystyle.html (or another style if don't want to fall back to the default style) and reimplement drawControl() http://doc.qt.io/qt-5/latest/qproxystyle.html#drawControl. In this function you need to handle the CE_HeaderLabel http://doc.qt.io/qt-5/latest/qstyle.html#ControlElement-enum case and draw the text manually after having rotated the painter.

The following is an example of how to do this:

#include <QtGui>
 
class MyStyle : public QProxyStyle
{
public:
    MyStyle(QStyle *style) : QProxyStyle(style) {}
    void drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, 
                     const QWidget *widget = 0) const
    {
        if (element == QStyle::CE_HeaderLabel) {
            const QHeaderView *hv = qobject_cast<const QHeaderView *>(widget);
            if (!hv || hv->orientation() != Qt::Vertical)
                return QProxyStyle::drawControl(element, option, painter, widget);
            const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(option);
            painter->save();
            painter->translate(header->rect.topLeft());
            painter->rotate(90);
            painter->drawText(0,0,header->text);
            painter->restore();
            return;
        }
        return QProxyStyle::drawControl(element, option, painter, widget);
    }
};
 
int main(int argc, char **argv)
{
    QApplication a(argc, argv);
    a.setStyle(new MyStyle(a.style()));
    QTableView tv;
    QStandardItemModel *sim = new QStandardItemModel(2,2,&tv);
    tv.setModel(sim);
    tv.show();
    return a.exec();
}

Why does not touching and moving work when running the imagegestures example on Windows 7?

Our gestures examples rely on the native Windows 7 gesture and touch input. If your driver doesn't generate these, then the examples won't work. One easy way to tell if it is the driver causing the problem is to put break points into the *WM_GESTURE* and *WM_TOUCH* message handlers in qapplication_win.cpp. If you hit those breakpoints, your driver supports the Windows 7 touch interface, but Qt doesn't work with it for some reason. In which case this should be reported via the usual channel http://bugreports.qt.io. Otherwise it is most likely an issue caused by your driver not implementing the Windows 7 touch interface.


How can I align the checkboxes in a view?

In order to align the checkboxes in a view, you need to create your own QStyledItemDelegate http://doc.qt.io/qt-5/latest/qstyleditemdelegate.html and reimplement paint() http://doc.qt.io/qt-5/qstyleditemdelegate.html#paint to draw the checkboxes with the alignment that you want.

In order to do this, QStyle::alignedRect() http://doc.qt.io/qt-5/latest/qstyle.html#alignedRect is used to ensure that it is correctly aligned in the center of the rect for the index, then the base implementation is called with the new information so it takes care of rendering the checkbox.

It is also necessary to reimplement QStyledItemDelegate::editorEvent() http://doc.qt.io/qt-5/qabstractitemdelegate.html#editorEvent to handle the toggling of the checkbox correctly since the checkbox has actually been moved to a different position, and therefore the events for the index need to be handled correctly.

The following example demonstrates how this can be done:

#include <QtGui>
 
class ItemDelegate : public QStyledItemDelegate
{
public:
    ItemDelegate(QObject *parent = 0)
        : QStyledItemDelegate(parent)
    {
    }
 
    void paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const
    {
        QStyleOptionViewItemV4 viewItemOption(option);
 
        if (index.column() == 0) {
            const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;
            QRect newRect = QStyle::alignedRect(option.direction, Qt::AlignCenter,
                                                QSize(option.decorationSize.width() + 5,option.decorationSize.height()),
                                                QRect(option.rect.x() + textMargin, option.rect.y(),
                                                      option.rect.width() - (2 * textMargin), option.rect.height()));
            viewItemOption.rect = newRect;
        }
        QStyledItemDelegate::paint(painter, viewItemOption, index);
    }
 
    virtual bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option,
                             const QModelIndex &index)
    {
        Q_ASSERT(event);
        Q_ASSERT(model);
 
        // make sure that the item is checkable
        Qt::ItemFlags flags = model->flags(index);
        if (!(flags & Qt::ItemIsUserCheckable) || !(flags & Qt::ItemIsEnabled))
            return false;
        // make sure that we have a check state
        QVariant value = index.data(Qt::CheckStateRole);
        if (!value.isValid())
            return false;
        // make sure that we have the right event type
        if (event->type() == QEvent::MouseButtonRelease) {
            const int textMargin = QApplication::style()->pixelMetric(QStyle::PM_FocusFrameHMargin) + 1;
            QRect checkRect = QStyle::alignedRect(option.direction, Qt::AlignCenter,
                                                  option.decorationSize,
                                                  QRect(option.rect.x() + (2 * textMargin), option.rect.y(),
                                                        option.rect.width() - (2 * textMargin),
                                                        option.rect.height()));
            if (!checkRect.contains(static_cast<QMouseEvent*>(event)->pos()))
                return false;
        } else if (event->type() == QEvent::KeyPress) {
            if (static_cast<QKeyEvent*>(event)->key() != Qt::Key_Space&& static_cast<QKeyEvent*>(event)->key() != Qt::Key_Select)
                return false;
        } else {
            return false;
        }
        Qt::CheckState state = (static_cast<Qt::CheckState>(value.toInt()) == Qt::Checked
                                ? Qt::Unchecked : Qt::Checked);
        return model->setData(index, state, Qt::CheckStateRole);
    }
};
 
static int ROWS = 3; static int COLS = 1;
 
class Table : public QTableWidget
{
    Q_OBJECT
public:
    Table(QWidget *parent = 0)
        : QTableWidget(ROWS, COLS, parent)
    {
        setItemDelegate(new ItemDelegate(this));
        QTableWidgetItem *item = 0;
        for (int i=0; i<rowCount(); ++i) {
            for (int j=0; j<columnCount(); ++j) {
                setItem(i, j, item = new QTableWidgetItem);
                item->setFlags(Qt::ItemIsEnabled|Qt::ItemIsUserCheckable);
                item->setCheckState((i+j) % 2 == 0 ? Qt::Checked : Qt::Unchecked);
            }
        }
    }
};
 
#include "main.moc"
 
int main(int argc, char **argv)
{
    QApplication a(argc, argv);
    Table w;
    w.show();
    return a.exec();
}

How can I dynamically switch between languages in my application using e.g a QComboBox?

In order to achieve this, you can create a function, called e.g retranslateUi() that sets the user visible text for your widgets. It is not possible to switch between the languages without having such a function that gets called every time the language is changed and that returns a translated version of the text by wrapping it with tr() http://doc.qt.io/qt-5/latest/qobject.html#tr.

Now you can connect the activated() http://doc.qt.io/qt-5/latest/qcombobox.html#activated signal of your QComboBox to a slot which will load and install the correct translator. Finally you also need to reimplement the changeEvent() http://doc.qt.io/qt-5/latest/qcombobox.html#changeEvent to check for a LanguageChange http://doc.trolltech.com/qevent.html#Type-enum event and call retranslateUi() when it occurs .

See the following example for a demonstration:

#include <QtGui>
class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow()
    {
        translator1 = new QTranslator(this);
        translator2 = new QTranslator(this);
        menu = new QMenu(this);
        menuBar()->addMenu(menu);
        fileAction = new QAction(this);
        menu->addAction(fileAction);
        QComboBox *combo = new QComboBox(this);
        setCentralWidget(combo); 
        combo->addItem("fr");
        combo->addItem("en");
        combo->addItem("sp");
        connect(combo, SIGNAL(activated(const QString &)), this, SLOT(changeMyLanguage(const QString &)));
        retranslateUi();
    }
    void retranslateUi()
    {
        menu->setTitle(tr("File"));
        fileAction->setText(tr("First action"));   
    }
    void changeEvent ( QEvent * event )
    {
        if (event->type() == QEvent::LanguageChange) {
            retranslateUi();
        }
        QMainWindow::changeEvent(event);
    }
    public slots:
        void changeMyLanguage(const QString & string)
        {
            if(string == QString("fr")) {
                translator1->load("t1_fr", ".");
                qApp->installTranslator(translator1);
            }
            if(string == QString("sp")) {
                translator2->load("t1_sp", ".");
                qApp->installTranslator(translator2);
            }
            if(string == QString("en")){
                qApp->removeTranslator(translator1);
                qApp->removeTranslator(translator2);
            }
        }
private:
    QAction *fileAction;
    QMenu *menu;
    QTranslator *translator1;
    QTranslator *translator2;
};
 
#include "main.moc"
 
int main(int argc, char **argv)
{
    QApplication a(argc, argv);
    MainWindow window;
    window.resize(50, 50);
    window.show();
    return a.exec();
}

When building Qt using MinGW I get the following error: Makefile.Debug:24691: *** multiple target patterns. What can be wrong?

You probably have some include and lib paths that are not necessary and are causing problems, if you do:

set INCLUDE=     
set LIB=     
configure -redo     
mingw32-make

that should solve the problem for you.

Also, make sure that sh.exe (usually comes with Cygwin or msys) is not in the PATH either, as MinGW's make tool expects UNIX-makefiles when it is.


How can I span the headers in my QTableView ?

Qt does not provide an API for spanning headers, but you can implement this yourself. You can subclass QHeaderView http://doc.qt.io/qt-5/latest/qheaderview.html and create one section for each of the groups of columns/rows you would like to span and connect signals and slots to have them react to the different columns/rows.

The following example demonstrates how this can be done for spanning thecolumns in the horizontal header.

#include <QtGui>
 
class MyHeaderModel : public QAbstractItemModel
{
public:
    MyHeaderModel(QObject *parent = 0) : QAbstractItemModel(parent) {}
    int columnCount(const QModelIndex &parent = QModelIndex()) const { return 2; }
    QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const { return QVariant(); }
    QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const { return QModelIndex(); }
    QModelIndex parent(const QModelIndex &index) const { return QModelIndex(); }
    int rowCount(const QModelIndex &parent = QModelIndex()) const { return 0; }
};
 
class MyHeader : public QHeaderView
{
    Q_OBJECT
public:
    MyHeader(QHeaderView *header, QWidget *parent = 0) : QHeaderView(Qt::Horizontal, header), mainHeader(header)
    {
        setModel(new MyHeaderModel(this));
        // This example uses hardcoded groups, you can extend
        // this yourself to save the groups
        // Group 1 is 0-2 and Group 2 is 3-4
        resizeSection(0, getSectionSizes(0, 2));
        resizeSection(1, getSectionSizes(3, 4));
        connect(this, SIGNAL(sectionResized(int,int,int)), this, SLOT(updateSizes()));
        connect(((QTableWidget *)(mainHeader->parentWidget()))->horizontalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(updateOffset()));
        setGeometry(0, 0, header->width(), header->height());
        updateOffset();
        mainHeader->installEventFilter(this);
    }
public slots:
    void updateSizes()
    {
        setOffset(mainHeader->offset());
        mainHeader->resizeSection(2, mainHeader->sectionSize(2) + (sectionSize(0) - getSectionSizes(0, 2)));
        mainHeader->resizeSection(4, mainHeader->sectionSize(4) + (sectionSize(1) - getSectionSizes(3, 4)));
    }
    void updateOffset()
    {
        setOffset(mainHeader->offset());
    }
protected:
    bool eventFilter(QObject *o, QEvent *e)
    {
        if (o == mainHeader) {
            if (e->type() == QEvent::Resize) {
                setOffset(mainHeader->offset());
                setGeometry(0, 0, mainHeader->width(), mainHeader->height());
            }
            return false;
        }
        return QHeaderView::eventFilter(o, e);
    }
private:
    int getSectionSizes(int first, int second)
    {
        int size = 0;
        for (int a=first;a<=second;++a)
            size += mainHeader->sectionSize(a);
        return size;
    }
    QHeaderView *mainHeader;
 
};
 
#include "main.moc"
int main(int argc, char **argv)
{
    QApplication a(argc, argv);
    QWidget w;
    QVBoxLayout *vbox = new QVBoxLayout;
    QTableWidget *tw = new QTableWidget(5, 5);
    MyHeader *h = new MyHeader(tw->horizontalHeader());
    vbox->addWidget(tw);
    w.setLayout(vbox);
    w.show();
    return a.exec();
}

How do I make text follow the line/curve and angle of the QPainterPath?

You can set a QTransform http://doc.qt.io/qt-5/qtransform.html on a QPainter http://doc.qt.io/qt-5/qpainter.html causing the painting to follow a transformation. The usual problem is that it's easy to rotate using QTransform::rotate() http://doc.qt.io/qt-5/4.7/qtransform.html#rotate, but since it rotates around origin which is in the top left corner, the coordinates will not match the painting done without a transformation. Using QTransform http://doc.qt.io/qt-5/qtransform.html translation, you can translate the positions back to the original position, and all of this in the name of trigonometry.

#include <QtGui>
#include <cmath>
 
class Widget : public QWidget
{
public:
    Widget ()
        : QWidget() { }
private:
    void paintEvent ( QPaintEvent *)
    {
        QString hw("hello world");
        int drawWidth = width() / 100;
        QPainter painter(this);
        QPen pen = painter.pen();
        pen.setWidth(drawWidth);
        pen.setColor(Qt::darkGreen);
        painter.setPen(pen);
 
        QPainterPath path(QPointF(0.0, 0.0));
 
        QPointF c1(width()*0.2,height()*0.8);
        QPointF c2(width()*0.8,height()*0.2);
 
        path.cubicTo(c1,c2,QPointF(width(),height()));
 
        //draw the bezier curve
        painter.drawPath(path);
 
        //Make the painter ready to draw chars
        QFont font = painter.font();
        font.setPixelSize(drawWidth*2);
        painter.setFont(font);
        pen.setColor(Qt::red);
        painter.setPen(pen);
 
        qreal percentIncrease = (qreal) 1/(hw.size()+1);
        qreal percent = 0;
 
        for ( int i = 0; i < hw.size(); i++ ) {
            percent += percentIncrease;
 
            QPointF point = path.pointAtPercent(percent);
            qreal angle = path.angleAtPercent(percent);
 
            qreal rad =qreal(0.017453292519943295769)*angle; // PI/180
 
            // From the documentation:
            /**
              QTransform transforms a point in the plane to another point using the following formulas:
              x' = m11*x + m21*y + dx
              y' = m22*y + m12*x + dy
            **/
            // So the idea is to find the "new position of the character
            // After we apply the world rotation.
            // Then translate the painter back to the original position.
            qreal sina = std::sin(rad);
            qreal cosa = std::cos(rad);
 
            // Finding the delta for the penwidth
            // Don't divide by 2 because some space would be nice
            qreal deltaPenX = cosa * pen.width();
            qreal deltaPenY = sina * pen.width();
            // Finding new posision after rotation
            qreal newX = (cosa * point.x()) - (sina * point.y());
            qreal newY = (cosa * point.y()) + (sina * point.x());
 
            // Getting the delta distance
            qreal deltaX = newX - point.x();
            qreal deltaY = newY - point.y();
            // Applying the rotation with the translation.
            QTransform tran(cosa,sina,-sina,cosa,-deltaX + deltaPenX,-deltaY - deltaPenY);
 
            painter.setWorldTransform(tran);
            painter.drawText(point,QString(hw[i]));
        }
    }
 
};
 
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    Widget widget;
    widget.show();
    return app.exec();
}

When I run my Qt for Embedded Linux application I get the error message Can't drive depth 32.

Your problem is most likely that you did not configure with support for the bit depth which the screen supports. To specify which bit depths you want Qt for Embedded Linux to support, use the configure option depths. For example:

./configure -qvfb -embedded x86 -debug -depths 8,16,32 -thread


I want to run my Qt for Embedded Linux application on the QVFb, but I get the message Can't open framebuffer device /dev/fb0 : driver cannot connect.

You must specify a -display option for the program as follows:

./fooprog -qws -display LinuxFb


Where do I put the plug-in library file for a touch screen driver plug-in?

The library should be put in yourQtDirectory/plugins/mousedrivers where it will be automatically found.


setClickable() and setSortIndicatorShown() affect the entire QHeaderView, is there a way to have it affect only certain sections?

There is no direct API for this at the moment, so for the time being, you need to reimplement the mousePressEvent() http://doc.qt.io/qt-5/latest/qheaderview.html#mousePressEvent and mouseReleaseEvent() http://doc.qt.io/qt-5/latest/qheaderview.html#mouseReleaseEvent for the headerview and check which section is being pressed on, then if it is one you want to allow to be movable, or clickable, you turn it on before calling the base implementation. In the mouseReleaseEvent() you would turn off the movable/clickable properties.

When it comes to setSortIndicatorShown() http://doc.qt.io/qt-5/latest/qheaderview.html#showSortIndicator-prop, then it is expected that the indicator will be shown until the user clicks on another section. So in mousePressEvent() we hide the indicator if the section clicked is not the one that should show the indicator. Alternatively the sort indicator can simply stay on the section clicked previously.

The example below demonstrates how this can be done.

#include <QtGui>
class HeaderView : public QHeaderView
{
    Q_OBJECT
public:
    HeaderView(QWidget *parent = 0) : QHeaderView(Qt::Horizontal, parent) 
    {
        connect(this, SIGNAL(sectionClicked(int)), this, SLOT(clickedSection(int)));
    }
    void mousePressEvent(QMouseEvent *event)
    {
        if(visualIndexAt(event->pos().x()) == 1) {
            setClickable(true);
            setSortIndicator(1, sortIndicatorOrder());
            setSortIndicatorShown(true);
        } else {
            setSortIndicatorShown(false);
            resizeSection(1, sectionSize(1) - 1);
            resizeSection(1, sectionSize(1) + 1);
        }
        QHeaderView::mousePressEvent(event);
    }
    void mouseReleaseEvent(QMouseEvent *event)
    {
        QHeaderView::mouseReleaseEvent(event);
        setClickable(false);
    }
public slots:
    void clickedSection(int s)
    {
        qDebug() << "Section " << s << " clicked";
    }
};
 
class TreeWidget : public QTreeWidget
{
public:
    TreeWidget()
    {
        setColumnCount(3);
        QStringList list;
        list << "a" << "b" << "c";
        QStringList list2;
        list2 << "d" << "e" << "f";
        QTreeWidgetItem *item1 = new QTreeWidgetItem(this, list);
        QTreeWidgetItem *item2 = new QTreeWidgetItem(this, list2);
        addTopLevelItem(item1);
        addTopLevelItem(item2);
        setHeader(new HeaderView(this));
    }
};
 
#include "main.moc"
 
int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    TreeWidget tree;
    tree.show();
    return app.exec();
}

How can I debug the Qt source files when running my application inside Visual Studio?

You can debug the Qt source files if you have made the relevant Qt modules, e.g QtCore and QtGui part of your solution.

If you are using the Visual Studio Add-in, then checking the Debugger Extension option while installing should have provided you with an autoexp.dat file in %VSINSTALLDIR%\Common7\Packages\Debugger that provides debugging support for the Qt classes. Make sure that this autoexp.dat file exists and that it contains an [AutoExpand] section that contains references to various Qt classes. If it does not exist, then uninstall and reinstall the Add-in.


How can QTextCursor be used to select a row in a QTextTable?

All that needs to be done to select the whole row is get the cells for the first and last column in the row, and then getting the relevant positions from those cells. With those positions you can select the text using setPosition() http://doc.qt.io/qt-5/latest/qtextcursor.html#setPosition and keeping the anchor. An example piece of code is as follows:

QTextTable *tt = textEdit->textCursor().currentTable();     
if (!tt)
    return;     
QTextCursor cursor = textEdit->textCursor();     
QTextTableCell cell = tt->cellAt(cursor);     
QTextTableCell rowStart = tt->cellAt(cell.row(), 0);     
QTextTableCell rowEnd = tt->cellAt(cell.row(), tt->columns() - 1);
cursor.setPosition(rowStart.firstCursorPosition().position());
cursor.setPosition(rowEnd.lastCursorPosition().position(), QTextCursor::KeepAnchor);        
textEdit->setTextCursor(cursor);

How do I apply patch files to Qt source files?

To apply a patch automatically you need a program called `patch'. `patch' takes a patch file containing a difference listing produced by diff and applies those differences to one or more original files, producing patched versions.

If you are running windows, you can download it from here:

http://gnuwin32.sourceforge.net/packages/patch.htm

On the Mac and on X11 a patch program is provided with the system.

http://gnuwin32.sourceforge.net/packages/patch.htm


When dragging and dropping between 2 views, how can I perform a move without pressing Shift?

When dragging and dropping between 2 views then a copy will be done by default when not pressing Shift. If you need to make it a Move action instead, then you can call

setDropAction(Qt::MoveAction)

in the dragEnterEvent() http://doc.qt.io/qt-5/latest/qabstractitemview.html#dragEnterEvent, dragMoveEvent() http://doc.qt.io/qt-5/latest/qlistview.html#dragMoveEvent and the dropEvent() http://doc.qt.io/qt-5/latest/qlistwidget.html#dropEvent. Doing so will override the proposed action http://doc.trolltech.com/dnd.html#overriding-proposed-actions.

See the following example for a demonstration:

#include <QtGui>  
 
class ListWidget : public QListWidget {     
Q_OBJECT
public:     
ListWidget() : QListWidget(0)     
{         
setAcceptDrops(true);
setDragEnabled(true);         
QListWidgetItem *item1 = new QListWidgetItem(tr("Oak"), this);         
QListWidgetItem *item2 = new QListWidgetItem(tr("Fir"), this);         
QListWidgetItem *item3 = new QListWidgetItem(tr("Pine"), this);     
}      
 
void dragEnterEvent(QDragEnterEvent *e)
{
QListWidget::dragEnterEvent(e);         
if (e->keyboardModifiers() == Qt::NoModifier) {             e->setDropAction(Qt::MoveAction);
e->accept();         
} else if (e->proposedAction() == Qt::MoveAction)
e->acceptProposedAction();     
}     
 
void dragMoveEvent(QDragMoveEvent *e)
{         
QListWidget::dragMoveEvent(e);         
if (e->keyboardModifiers() == Qt::NoModifier) {             e->setDropAction(Qt::MoveAction);
e->accept();
} else if (e->proposedAction() == Qt::MoveAction)
e->acceptProposedAction();
}     
 
void dropEvent(QDropEvent *e)    
 {
if (e->keyboardModifiers() == Qt::NoModifier) {
QListWidget::dropEvent(e);             
e->setDropAction(Qt::MoveAction);
e->accept();                     
} else if (e->proposedAction() == Qt::MoveAction) {             
QListWidget::dropEvent(e);
e->acceptProposedAction();             
} else
QListWidget::dropEvent(e);     
}  
};  
 
#include "main.moc"  
 
int main(int argc, char **argv) 
{     
QApplication app(argc, argv);     
QWidget wid;
ListWidget *box = new ListWidget;     
ListWidget *box2 = new ListWidget
QVBoxLayout layout(&wid);
layout.addWidget(box);     
layout.addWidget(box2);     
wid.show();
return app.exec();     
}

How can I get rid of the sizegrip of a window on Mac OS X?

Qt/Mac uses the sizegrip given from Mac OS X. When calling

statusBar()->setSizeGripEnabled(true)

the status bar creates a QSizeGrip http://doc.qt.io/qt-5/latest/qsizegrip.html, hides the native Mac OS X size grip, and places the QSizeGrip in the same location as the native size grip. If you don't want any sizegrip to appear, then you need to give your window a fixed size. If you don't want to give your window a fixed size, then you can use the QSizeGrip provided by Qt and call setFixedSize(0,0) on that one, e.g:

#include <QtGui>
 
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    #if 1
    QMainWindow box;
    box.statusBar()->setSizeGripEnabled(true);
    QSizeGrip *grip = box.statusBar()->findChild<QSizeGrip*>();
    #else
    QDialog box;
    QStatusBar *grip = new QStatusBar(&box);
    #endif
    box.show();
    grip->setFixedSize(0,0);
    return app.exec();
}

How do I add a custom Info.plist to my Mac application with qmake?

You can set your own Info.plist by setting the QMAKE_INFO_PLIST variable to your Info.plist file. qmake will add a rule in the Makefile it generates to copy this over. If you don't specify this, qmake provides a generic Info.plist file.

QMAKE_INFO_PLIST = MyInfo.plist   # qmake will copy this file to MyApp.app/Contents/Info.plist


How often will new Qt SDK packages be released?

A new SDK package will be released each time a new Qt version is released, or when a new minor version (1.x) of Qt Creator is released.


Why is it only possible to draw in the GUI thread and how can this be worked around?

X11 does rendering in a single thread so even if you use different threads to draw, the drawing will be serialized in the X server thread, so there is no benefit from drawing in different threads.

On Windows the same is true. Since Qt normally relies on the underlying Windowing System, we don't provide this option. However, we do provide the option to render into a QImage from a Non-GUI thread, as this is a pure software solution only partially relying on the underlying system. It is also possible to do multi-threaded text layout and printing, see:

http://blog.qt.io/2007/09/27/multi-threaded-text-layout-and-printing/

Please note that unless your software is running on machines that have multiple CPU's, splitting rendering into threads will not give you any significant speed improvements (we have experiences that hyper threading usually slows performance down in a single application)

According to our measurements, you can on a desktop computer draw approximately 500 000 triangles (10*10 pixels) per second.


How can I make the text of a disabled widget look enabled?

In order to make the text of a disabled widget look enabled, you can change the color of the disabled colorgroup in the palette to have the same color as the active color group. See the documentation on QPalette::setColor() http://doc.qt.io/qt-5/qpalette.html#setColor

The following example demonstrates how this can be done for a QLineEdit http://doc.qt.io/qt-5/latest/qlineedit.html:

#include <QtGui>  
 
int main(int argc, char **argv)
{     
QApplication app(argc, argv);     
QLineEdit edit;     
edit.setText("Lineedit");
edit.setDisabled(true);     
QPalette pal = edit.palette();
pal.setColor(QPalette::Disabled, QPalette::Text, pal.color(QPalette::Active, QPalette::Text));     
pal.setColor(QPalette::Disabled, QPalette::Base, pal.color(QPalette::Active, QPalette::Base));     
edit.setPalette(pal);
edit.show();     
return app.exec();
}

Why do you provide container classes as an alternative to STL in Qt?

We want our container classes to behave in the same way on all platforms. The different compilers might have different implementations of STL, so the behavior can vary. In addition when we created the container classes, not all platforms had decent implementations of STL. Finally, we provide QString http://doc.qt.io/qt-5/latest/qstring.html which is a string class which provides a string of unicode characters. Since QString is available on all platforms, we can be sure that it will work for passing unicode characters from one place to another.


How do I create a default size for the rows in a table view?

In order to change the default size for the rows in a table view, you need to reimplement sizeHintForRow() http://doc.qt.io/qt-5/qtableview.html#sizeHintForRow and make sure resizeRowToContents() http://doc.qt.io/qt-5/qtableview.html#resizeRowToContents is called.

The example below demonstrates how this can be achieved

#include <QtGui>
 
class Model : public QAbstractTableModel
{
public:
  Model(QObject *parent) 
  {
    QStringList firstRow;
    QStringList secondRow;
 
    for (int i = 0; i < 5; i++ ) {
      firstRow.insert(i,"Row 1 " + QString::number(i+1));
      secondRow.insert(i,"Row 2 " + QString::number(i+1));
    }
 
    stringList << firstRow << secondRow;
  }
  // Returns the number of rows
  int rowCount ( const QModelIndex & parent = QModelIndex() ) const
  {
    return stringList.count();
  }
 
  // Returns the number of columns
  int columnCount ( const QModelIndex & parent = QModelIndex() ) const
  {
    return stringList[0].count();
 
  }
 
 
  // Returns an appropriate value for the requested data.
  // If the view requests an invalid index or if the role is not
  // Qt::DisplayRole, an invalid variant is returned.
  // Any valid index that corresponds to a string for the index's column and row in
  // the stringlist is returned
  QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const 
  {
    if (!index.isValid())
      return QVariant();
    if (role != Qt::DisplayRole)
      return QVariant();
    QStringList list = (QStringList)stringList.at(index.row());
    return list.at(index.column());        
  }
private:
  QList<QStringList>stringList;
 
};
 
class TableView : public QTableView
{
public:
  TableView(QWidget *parent) {}
 
  //Returns the needed size for the rows
  int sizeHintForRow ( int row ) const
  {
    return 200;
  }
};
 
 
int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  QWidget widget;
  QHBoxLayout *layout = new QHBoxLayout(&widget);
  TableView *tableView = new TableView(&widget);
  Model *model = new Model(tableView);
  tableView->setModel(model);
  for (int i = 0; i < model->rowCount(); i++) {
    tableView->resizeRowToContents(i); 
  }
 
  layout->addWidget(tableView);
 
  widget.show();
  return app.exec(); 
}

How can I embed e.g a QMainWindow inside a QDialog ?

In order to embed a toplevel window inside another window you need to create the embedded window without a parent and then call setParent() http://doc.qt.io/qt-5/latest/qwidget.html#setParent on it after the embedded window has been constructed.

See the following example for an illustration:

#include <QtGui>
 
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QDialog box;
    QMainWindow *window = new QMainWindow(0);
    QTextEdit *edit = new QTextEdit(window);
    window->setCentralWidget(edit);
 
    QVBoxLayout *layout = new QVBoxLayout(&box);
    layout->addWidget(window);
    QMenu *menu = new QMenu("file", window);
    menu->addAction("one");
    menu->addAction("one");
    menu->addAction("one");
 
    window->menuBar()->addMenu(menu);
    window->setParent(&box);
    return box.exec();
}

How do I set the width or height of the header sections in a view?

You can set the width or height of the header sections in a view by calling QHeaderView::resizeSection() http://doc.qt.io/qt-5/latest/qheaderview.html#resizeSection. The QHeaderView class provides a header row or header column for item views, and you can use the header() http://doc.qt.io/qt-5/latest/qtreeview.html#header, horizontalHeader() http://doc.qt.io/qt-5/latest/qtableview.html#horizontalHeader or verticalHeader() http://doc.qt.io/qt-5/latest/qtableview.html#verticalHeader (depending on what your view is) functions to access them.

#include <QApplication>
#include <QTableWidget>
#include <QHeaderView>
 
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QTableWidget table(2,2);
 
     QTableWidgetItem *itemOne = new QTableWidgetItem("one");
     table.setItem(0,0,itemOne);
 
     table.horizontalHeader()->resizeSection(0, 200);
     table.verticalHeader()->resizeSection(1, 200);
 
     table.show();
     return app.exec();    
}

How can I sort the items in a QTableWidget on multiple columns?

This will depend a little on the size of your dataset. Since we use a stable sort you can relatively easily achieve this by keeping a list of sort columns and sort them from last to first.

See the example below for a demonstration.

If you have a lot of records you might want to implement your own model that will more efficiently sort based on multiple columns.

#include <QtGui>
 
#define SETPERSON(index, first, second, salary)     setItem(index, 0, new QTableWidgetItem(first));    
setItem(index, 1, new QTableWidgetItem(second));    
setItem(index, 2, new QTableWidgetItem);    
item(index, 2)->setData(Qt::DisplayRole, salary);
 
class Table : public QTableWidget
{
    Q_OBJECT
public:
    Table(QWidget *parent = 0)
        : QTableWidget(6, 3, parent)
    {
        SETPERSON(0, "Jerry", "Springer", 1000000);
        SETPERSON(1, "Foo", "Springer", 12341);
        SETPERSON(2, "John", "Wayne", 12341);
        SETPERSON(3, "Bob", "Carver", 80000);
        SETPERSON(4, "Bob", "Carver", 81000);
        SETPERSON(5, "Bob", "Ulong", 60000);
        updateSortOrder();
        connect(horizontalHeader(), SIGNAL(sectionClicked(int)),
                this, SLOT(onHeaderClicked(int)));
        disconnect(horizontalHeader(), SIGNAL(sectionPressed(int)), this, SLOT(selectColumn(int)));
 
    }
 
    void updateSortOrder()
    {
        QStringList list;
        list << "First name" << "Last name" << "Salary";
        for (int i=0; i<sortOrder.size(); ++i)
            list[sortOrder.at(i).column].append("(" + QString::number(i + 1) + ")");
        setHorizontalHeaderLabels(list);
        for (int i=sortOrder.size() - 1; i>=0; --i) {
            sortItems(sortOrder.at(i).column, sortOrder.at(i).ascending ? Qt::AscendingOrder : Qt::DescendingOrder);
        }
    }
public slots:
    void onHeaderClicked(int section)
    {
        bool ascending = true;
        if (!(QApplication::keyboardModifiers() & Qt::ControlModifier) || sortOrder.isEmpty()) {
            if (!sortOrder.isEmpty() && sortOrder.first().column == section) {
                ascending = !sortOrder.first().ascending;
            }
            sortOrder.clear();
        } else {
            const int index = findSection(section);
            if (index != -1) {
                if (index == sortOrder.size() - 1) {
                    ascending = !sortOrder.last().ascending;
                }
                sortOrder.removeAt(index);
            }
    }
        sortOrder.append(SortData(section, ascending));
        updateSortOrder();
    }
private:
    int findSection(int section) const
    {
        for (int i=0; i<sortOrder.size(); ++i) {
            if (sortOrder.at(i).column == section)
                return i;
        }
        return -1;
    }
    struct SortData {
        SortData(int sec = -1, bool asc = true) : column(sec), ascending(asc) {}
 
        int column;
        bool ascending;
    };
    QList<SortData> sortOrder;
};
 
#include "main.moc"
 
int main(int argc, char **argv)
{
    QApplication a(argc, argv);
    Table w;
    w.show();
    return a.exec();
}

How can I translate the application menu on the Mac?

You need to do a little extra to get this working. This is a requirement of Mac OS X and not of Qt. You can find information on this here http://doc.qt.io/qt-5/mac-differences.html#translating-the-application-menu-and-native-dialogs.

Since the application menu is not really controlled by Qt, you have to play by the rules of the operating system. If you want the menu to show up in e.g German then you can simply create a folder called de.lproj and put that in the yourApp.app/Contents/Resources folder in your bundle. Inside the de.lproj folder you put the localisation.plist which should have contents similar to that shown in the documentation. So if you want the menu to show up in German, simply change the value of the

<key>LprojLocale</key> to de.


You can take a look at the contents of many of your applications installed in /Applications. They should be similar to what's described here.


When popping up a context menu, how can I get hold of the cell where the menu popped up in my view?

When reimplementing the contextMenuEvent() http://doc.qt.io/qt-5/latest/qabstractscrollarea.html#contextMenuEvent in a view to pop up a menu where the cursor is located, then you can pass in the cursor's global position as an argument to exec() http://doc.qt.io/qt-5/latest/qmenu.html#exec. For determining which cell was clicked then simply use the event's pos() http://doc.qt.io/qt-5/latest/qcontextmenuevent.html#pos value as an argument to indexAt() http://doc.qt.io/qt-5/latest/qtableview.html#indexAt and get the QModelIndex that way.

The example below demonstrates how this can be done for a QTableView:

#include <QtGui>
 
class Model : public QAbstractTableModel
{
public:
    Model(QObject *parent) : QAbstractTableModel(parent)
    {
        QStringList firstRow;
        QStringList secondRow;
        for (int i = 0; i < 15; i++ ) {
            firstRow.insert(i,"Row 1 " + QString::number(i+1));
            secondRow.insert(i,"Row 2 " + QString::number(i+1));
        }
        stringList << firstRow << secondRow;
    }
 
    int rowCount ( const QModelIndex & parent = QModelIndex() ) const
    {
        return stringList.count();
    }
 
    int columnCount ( const QModelIndex & parent = QModelIndex() ) const
    {
        return stringList[0].count();
    }
 
    QVariant data ( const QModelIndex & index, int role = Qt::DisplayRole ) const 
    {
        if (!index.isValid())
            return QVariant();
        if (role != Qt::DisplayRole)
            return QVariant();
        QStringList list = (QStringList)stringList.at(index.row());
        return list.at(index.column());        
    }
private:
    QList<QStringList>stringList;
 
};
 
class TableView : public QTableView
{
public:
    TableView(QWidget *parent) : QTableView(parent)
    {}
 
    void contextMenuEvent ( QContextMenuEvent * e )
    {
        QMenu *menu = new QMenu(this);
        QModelIndex index = indexAt(e->pos());
        if (index.isValid())
          menu->addAction(QString("Row %1 - Col %2 was clicked on").arg(index.row()).arg(index.column()));
        else
          menu->addAction("No item was clicked on");
        menu->exec(QCursor::pos());
    }
};
 
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QWidget widget;
    QHBoxLayout *layout = new QHBoxLayout(&widget);
 
    TableView *tableView = new TableView(&widget);
    Model *model = new Model(tableView);
    tableView->setModel(model);
    layout->addWidget(tableView);
 
    widget.show();
    return app.exec(); 
}

Intellisense does not work for my Qt application. What's wrong?

When writing code that uses the class generated from a ui file, the intellisense does not appear to list the functions for it.

There are several reason why this happens:

1. You are currently in the function body in a slot. The VS intellisense parser gets confused by the slot keyword in the header file and stops therefore working. As an easy workarround for this just place a ';' behind the slots declaration, e.g.:


public slots:;

    void mySlot();

2. The class/struct is not directly included. Sometimes the completion on e.g. a push button object does not work since you included <QtGui>. For compilation it's of course perfect, but intellisense may not work correctly with this information. Try to include <QtGui/QPushButton> instead/in addition.

3. The C++ source code has not been generated yet. Intellisense works only on C++ code, but when designing a form there is no C++ code directly involved. The C++ code is generated by uic which must be run after the ui file is saved. So, whenever you added or removed an item from the form you have to run uic on it. This can easily be done by opening the context menu for the ui file in the solution explorer and clicking on compile. Another, more comfortable, way of doing this is enabling the AutoRunUic property in Tools|Options|Qt|General options page. This basically saves the form and runs uic whenever you leave the form editor.

4. Make sure you open Visual Studio using the command prompt provided with Qt in the Start menu if you are using the binary package or from a command prompt that has the environment set correctly if you are using the source package.

If it's only happening with a specific project, then try deleting (or renaming to be safe) the .ncb and .suo file for that project. These will be regenerated when the project is opened and built, respectively, and could help if the problem is due to some sort of corruption in those files.


Is it possible to reimplement non-virtual slots?

When a class is subclassed and a slot is reimplemented, regardless of whether it is virtual or not, the meta object for the subclass is the one that is queried for the slot and therefore it actually finds the reimplemented slot.

There can be situations where your reimplemented slot does not get called however. If the connections for the slot are created in the base class's constructor for example, then it is not able to access the subclass's metaobject since the virtual table isn't ready at this point and since metaObject() http://doc.qt.io/qt-5/qobject.html#metaObject is a virtual function it will end up with the base class's implementation of it. Since you cannot get the reimplemented virtual function of a class in its base class constructor you need to trigger the connections to be set up again at a point where the metaobject of the subclass can be gotten hold of.

In the example below, we have reimplemented columnResized() http://doc.qt.io/qt-5/qtableview.html#columnResized for a QTableWidget subclass. Since the connection for columnResized() is set up indirectly from the QTableWidget's constructor (in the setHorizontalHeader() http://doc.qt.io/qt-5/4.7/qtableview.html#setHorizontalHeader function), then we need to trigger setHorizontalHeader() to get called again after the tablewidget subclass is constructed. We do this by creating a new header and setting it up in a slot connected to a single shot timer.

#include <QtGui>
 
class TableWidget : public QTableWidget
{
    Q_OBJECT
public:
    TableWidget() : QTableWidget(10, 10)
    {
        QTimer::singleShot(0, this, SLOT(fixHeader()));
    }
 
public slots:
    void fixHeader()
    {
        QHeaderView *hv = new QHeaderView(Qt::Horizontal, this);
        hv->setHighlightSections(true);
        hv->setClickable(true);
        setHorizontalHeader(hv);
        hv->show();
    }
protected slots:
 
    void columnResized(int a, int b, int col)
    {
        qDebug() << "This is called";
    }  
};
 
#include "main.moc"
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    TableWidget box;
    box.show();
    return app.exec();    
}

When running on Linux then Eclipse crashes frequently. The 'problematic frame' seems to be 'gtk_tooltips_set_tip+0x1dc'. What is the problem ?

This is a problem of Eclipse on certain platforms, and is not related to the Qt Eclipse Integration. See for example here:

https://bugs.launchpad.net/ubuntu/+source/eclipse/+bug/128232


Does Qt for Embedded Linux support mouse shortcuts?

Yes. The following shortcuts are supported:

  • double-click the title bar
  • right-click to expose menus
  • shift-click to select consecutive list items or text
  • ctrl-click to select non-consecutive list items
  • click-n-drag to select text
  • double-click to select a word of text


How can I make a QComboBox have multiple selection?

With the example given below, you can currently do multiple selection by dragging the mouse over the items you want to select. There is only one thing left that needs to be done, and that's to decide how you want to make the combobox's popup disappear. This is not illustrated in the example, but all you need to do is install an event filter on the view for the combobox and when you get a mouse button release, you can either eat the event or let it carry on. Eating it would prevent it from closing the popup and therefore allow you to close it when you want. As long as you call hidePopup() http://doc.qt.io/qt-5/qcombobox.html#hidePopup when you want it to be closed, then it will ensure that everything is updated as appropriate.

#include <QtGui>
 
class MyComboBox : public QComboBox
{
    Q_OBJECT
public:
    MyComboBox(QWidget *parent = 0) : QComboBox(parent)
    {
        addItem("A");
        addItem("B");
        addItem("C");
        setEditable(true);
        lineEdit()->setReadOnly(true);
        view()->setSelectionMode(QAbstractItemView::MultiSelection);
    }
    void showPopup()
    {
        QComboBox::showPopup();
        QStringList strs = str.split(" ");
        QAbstractItemModel *model = view()->model();
        for (int i=0;i<strs.size();++i) {
            QModelIndexList idxes = model->match(model->index(0, 0), Qt::DisplayRole, strs.at(i), 1, 
                                                 Qt::MatchExactly);
            foreach(QModelIndex idx, idxes)
                view()->selectionModel()->select(idx, QItemSelectionModel::Select);
        }
    }
    void hidePopup()
    {
        QItemSelectionModel *ism = view()->selectionModel();
        QModelIndexList idxes = ism->selectedIndexes();
        str = "";
        foreach(QModelIndex idx, idxes)
            str += idx.data().toString() + " ";
        QComboBox::hidePopup();
        QTimer::singleShot(0, this, SLOT(updateText()));
    }
public slots:
    void updateText()
    {
        lineEdit()->setText(str);
    }
private:
    QString str;
};
 
#include "main.moc"
 
int main(int argc, char **argv)
{
    QApplication a(argc, argv);
    MyComboBox b;
    b.show();
    return a.exec();
}

How can I draw vertical text?

Drawing vertical text can be done in several ways. The easiest way might be to create a QTextDocument http://doc.qt.io/qt-5/latest/qtextdocument.html in the paintEvent() http://doc.qt.io/qt-5/latest/qwidget.html#paintEvent and use setHtml() http://doc.qt.io/qt-5/latest/qtextdocument.html#setHtml to set the text and specify the

<br>

tag to get line breaks. Another way could be to iterate over the QChars http://doc.qt.io/qt-5/latest/qchar.html in the QString http://doc.qt.io/qt-5/latest/qstring.html and position them vertically in the paintEvent() yourself. Then you would need to calculate the height between each element.

If what you want is rotated text, then you can simply rotate the painter 90 degrees.

Finally, if you are not going to draw the text yourself, then a QLabel http://doc.qt.io/qt-5/latest/qlabel.html can easily be used to display vertical text, simply by specifying \n after each character.

The example below illustrates some of the possibilities:

#include <QtGui>
 
class Widget : public QWidget
{
public:
  Widget(QWidget *parent = 0)
    : QWidget(parent)
  {}
 
  void paintEvent(QPaintEvent *)
  {
    QPainter p(this);
#if 1  
    QTextDocument document;
    document.setHtml("<br>T<br>e<br>s<br>t<br>");
    document.drawContents(&p);
#else  
    drawRotatedText(&p, 90, width() / 2, height() / 2, "The vertical text");
#endif
  }
 
  void drawRotatedText(QPainter *painter, float degrees, int x, int y, const QString &text)
  {
    painter->save();
    painter->translate(x, y);
    painter->rotate(degrees);
    painter->drawText(0, 0, text);
    painter->restore();
  }
};
int main(int argc, char **argv)
{
  QApplication a(argc, argv);
  Widget w;
  w.resize(200,200);
  QString string = "t\ne\ns\nt";
  QLabel label;
  label.setText(string);
  label.show();
  w.show();
  return a.exec();
}

I would like to detect if the expansion sign has been clicked in my QTreeView. How can this be achieved?

If you want to be notified when the user clicks the expansion button for the items in your tree, then you can reimplement the mousePressEvent() http://doc.qt.io/qt-5/latest/qtreeview.html#mousePressEvent and calculate the position of the expansion sign. If the mouse is over the calculated position, then you can for example emit a signal to notify it and do your own handling. Otherwise, simply call the base implementation.

The following example demonstrates how this can be done:

#include <QtGui>
 
class TreeWidget : public QTreeWidget
{
public:
    TreeWidget()
    {
        setColumnCount(1);
        item1 = new QTreeWidgetItem(this);
        item1->setText(0, "item 1");
        item1->setExpanded(true);
 
        item2 = new QTreeWidgetItem(item1);
        item2->setText(0, "item 2");
        item2->setExpanded(true);
        item3 = new QTreeWidgetItem(item2);
        item3->setText(0, "item 3");
        item4 = new QTreeWidgetItem(item1);
        item4->setText(0, "item 4");
    }
    void mousePressEvent(QMouseEvent *event)
    {
        QModelIndex indexClicked = indexAt(event->pos());
        if(indexClicked.isValid())
        {
            QRect vrect = visualRect(indexClicked);
            int itemIndentation = vrect.x() - visualRect(rootIndex()).x();
 
            QRect rect = QRect(header()->sectionViewportPosition(0) + itemIndentation - 
                indentation(), vrect.y(), indentation(), vrect.height());
 
            if(rect.contains(event->pos()) && model()->hasChildren(indexClicked)) {
                qDebug() << "plus clicked";
                QTreeWidget::mousePressEvent(event);
                return;
            } else {
                QTreeWidget::mousePressEvent(event);
            }
        }
    }
private:
    QTreeWidgetItem *item1;
    QTreeWidgetItem *item2;
    QTreeWidgetItem *item3;
    QTreeWidgetItem *item4;
};
 
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    TreeWidget box;
    box.show();
    return app.exec();    
}

How can I catch Alt+F4 in my Qt application ?

Alt+F4 is a key combination controlled by Windows and Qt has no control over such system keys. What you can try to get around this is to start a QTimer to calculate the time from when Alt is pressed until the widget receives a closeEvent() http://doc.qt.io/qt-5/qwidget.html#closeEvent. If the closeEvent() http://doc.qt.io/qt-5/qwidget.html#closeEvent is received before e.g 300 msecs have passed, you can assume that Alt+F4 was pressed. See the following example for an illustration:

#include <QtGui>
 
class MainWindow : public QMainWindow
{
	Q_OBJECT
public:
	MainWindow() : QMainWindow()
	{
		altPressed = false;
		installEventFilter(this);
	}
 
	void closeEvent(QCloseEvent *event)
	{
		if (altPressed) {
			qDebug() << Alt + f4 was pressed, causing shutdown;
		} else {
			qDebug() << Alt + f4 was not pressed. Shutting down for another reason;
		}
                QMainWindow::closeEvent(event);
         }
	bool eventFilter(QObject *o, QEvent *e)
	{
		if (e->type() == QEvent::ShortcutOverride) {
			QKeyEvent *event = (QKeyEvent *)e;
			if(event->modifiers() == Qt::AltModifier) {
				altPressed = true;
				QTimer::singleShot(300, this, SLOT(testSlot()));
				return false;
			}
		}
		return QMainWindow::event(e);
	}
	public slots:
		void testSlot()
		{
			qDebug() << Only Alt was pressed;
			altPressed = false;
		}
private:
	bool altPressed;
 
};
#include main.moc"
int main(int argc, char **argv)
{
	QApplication app(argc, argv);
	MainWindow main;
	main.show();
	return app.exec();
}

When running a Qt application on the French translation of Mac OS X, About shows up instead of A propos in the application menu. What is wrong ?

The reason why About shows up instead of A propos in this situation is that the About text is set by Qt. Preferences, Quit, etc are given the standard Carbon commands, so Carbon can detect which language to display them in provided that you have the correct .lproj in your application bundle. Since there is no general way to translate the About text, you can provide the text you want by subclassing QTranslator http://doc.qt.io/qt-5/latest/qtranslator.html and reimplementing translate() http://doc.qt.io/qt-5/qtranslator.html#translate to return the text you want.

See the following example for an illustration:

#include <QtGui>  
 
class Translator : public QTranslator 
{      
    Q_OBJECT
public:
    Translator(QWidget* parent=0) : QTranslator(parent) {}
    QString translate(const char *context, const char *sourceText, 
                      const char *comment = 0) const         
    {                 
        if (QString(context).compare("QMenuBar") == 0 && 
            QString(sourceText).compare("About %1") == 0)  {
            return QString("Apropos d' %1");                 
        }
        return sourceText;
    } 
};  
 
#include "main.moc"  
 
int main(int argc, char** argv) 
{     
    QApplication app(argc, argv);     
    Translator translator;
    app.installTranslator(&translator);          
    QMainWindow window;     
    QMenu *menu = window.menuBar()->addMenu("Test");     
    QAction *firstAction = menu->addAction(QObject::tr("Random text"));
    firstAction->setMenuRole(QAction::AboutRole);     
    QAction *secondAction = menu->addAction(QObject::tr("Preferences"));
    secondAction->setMenuRole(QAction::PreferencesRole);     
    window.show();
    return app.exec();           
}

How can I have a partially transparent pixmap on my toplevel window?

For top level windows we only support constant transparency and masking, so to achieve this effect, you can do one out of two things:

  1. Extract the transparent areas from the image as a bitmap and set this as the widget mask. This will not allow you to have partially transparent areas.
  2. If you want to show a QPixmap http://doc.qt.io/qt-5/latest/qpixmap.html with an alpha as your splash screen, then you

can use this approach which is slightly less efficient. You need to figure out the geometry of your splashscreen and use QPixmap::grabWindow() http://doc.qt.io/qt-5/latest/qpixmap.html#grabWindow to fetch this area into a QPixmap. Then take your pixmap and blend it on top of the grabbed pixmap. The resulting pixmap you can set as the widget pixmap.

#include <QtGui>
 
class Widget : public QWidget
{
public:
  Widget()
  {
    setWindowFlags(Qt::FramelessWindowHint);
    transparentPixmap = QPixmap("pixmap with an alpha");
    desktopBackground= QPixmap::grabWindow(0, x(), y(), width(),height());
  }
  void paintEvent(QPaintEvent *event)
  {
    QPainter painter(this);
    painter.drawPixmap(0, 0, desktopBackground);
    painter.drawPixmap(0,0, transparentPixmap );
  }
  void resizeEvent(QResizeEvent *event)
  {
    setWindowOpacity(0.0);
    desktopBackground= QPixmap::grabWindow(0, x(), y(), width(),height());
    setWindowOpacity(1.0);
    update();
  }
private:
  QPixmap desktopBackground;
  QPixmap transparentPixmap;
};
int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  Widget box;
  box.resize(255, 255);
  box.show();
  return app.exec();
}

How can I do multiselection in a QCalendarWidget?

There is no direct API for doing multi selection in a QCalendarWidget http://doc.qt.io/qt-5/latest/qcalendarwidget.html. What you can do however is to install an event filter on the viewport of the QTableView http://doc.qt.io/qt-5/latest/qtableview.html which is used by the QCalendarWidget and check to see if the Shift modifier is pressed and if so select the relevant QModelIndexes http://doc.qt.io/qt-5/latest/qmodelindex.html. The example below demonstrates how this can be done. Note that the example will need some tweaking if you want to use it. It does for example only work when selecting forwards, not when selecting backwards.

#include <QtGui>
 
class CalendarWidget : public QCalendarWidget {
  Q_OBJECT
public:
  CalendarWidget(QWidget *parent = 0) : QCalendarWidget(parent)
  {
    view = qFindChild<QTableView *>(this);
    view->viewport()->installEventFilter(this);
  }
 
  bool eventFilter(QObject *obj, QEvent *event)
  {
    if (obj->parent() && obj->parent() == view) {
      if (event->type() == QEvent::MouseButtonPress ||
        event->type() == QEvent::MouseButtonRelease) {
          QMouseEvent *me = static_cast<QMouseEvent*>(event);
          QPoint pos = me->pos();
          if (event->type() == QEvent::MouseButtonPress &&
            !(me->modifiers() & Qt::ShiftModifier)) {
              QModelIndex idx = view->indexAt(pos);
              if (idx.row() != 0 && idx.column() != 0)
                startIndex = idx;
          } else if (event->type() == QEvent::MouseButtonRelease && 
            me->modifiers() & Qt::ShiftModifier) {
              QModelIndex idx = view->indexAt(pos);
              if (idx.row() != 0 && idx.column() != 0)
                endIndex = idx;
              else
                return false;
              if (!startIndex.isValid())
                startIndex = 
                view->selectionModel()->selectedIndexes().first();
              endIndex = view->indexAt(pos);
              int rowStart = startIndex.row();
              int rowEnd = endIndex.row();
              int colStart = startIndex.column();
              int colEnd = endIndex.column();
              QItemSelection sel;
              for (int i=rowStart;i<=rowEnd;i++) {
                if (i == rowStart && i != rowEnd) {
                  for (int j=colStart;
                    j<view->model()->columnCount();j++)
                    view->selectionModel()->select(
                    view->model()->index(i, j),
                    QItemSelectionModel::Select);
                } else if (i == rowEnd) {
                  int start = (i == rowStart) ? colStart : 1;
                  for (int j = start;j<colEnd;j++)
                    view->selectionModel()->select(
                    view->model()->index(i, j),
                    QItemSelectionModel::Select);
                } else {
                  for (int j=1;j<view->model()->columnCount();j++)
                    view->selectionModel()->select(
                    view->model()->index(i, j),
                    QItemSelectionModel::Select);
                }
              }
              view->selectionModel()->select(endIndex,
                QItemSelectionModel::Select);
              return true;
          }
      }
      return false;
    } else {
      return QCalendarWidget::eventFilter(obj, event);
    }
  }
 
private:
  QTableView *view;
  QPersistentModelIndex startIndex;
  QPersistentModelIndex endIndex;
};
 
#include "main.moc"
 
int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  CalendarWidget calendar;
  calendar.show();
  return app.exec();
}

Is it possible to install and run Qt for Embedded Linux on a headless machine?

Yes. Remote display is possible by using Qt for Embedded Linux's VNC drivers.


Does Qt for Embedded Linux support keyboard navigation?

Yes. Qt for Embedded Linux supports the following:

  • Tab groups
  • Alt-F4
  • Alt-Tab
  • Shift-Alt-Tab
  • arrow (for radio button groups)
  • spacebar (for radio button or checkbox select)
  • Alt-spacebar (for window menu)
  • Shift-Ctrl-arrow and Shift-arrow (to highlight characters)-
  • Windows-key-D (minimize all windows)
  • Esc (remove dialog or menu)


Does the Qt for Embedded Linux windowing system support standard window operations?

Qt for Embedded Linux supports the following operations:

  • minimize
  • maximize/restore
  • close
  • resize by click-n-drag (horizontal, vertical, or both)
  • reposition by click-n-drag
  • select the active window by clicking on it


How does Qt for Embedded Linux access the display?

Qt for Embedded Linux comes with some graphics drivers, but most of Qt for Embedded Linux applications access the Linux video frame buffer directly. Specific accelerated drivers can also be implemented in Qt for Embedded Linux, as plug-in, to improve performances. Such drivers access the graphics hardware directly to utilize any available hardware acceleration of graphics operations.


Why can't I debug the Qt sources when using the Qt SDK?

When selecting the default option when installing the Qt SDK, the sources are not included in the installation. You need to choose the custom option and ensure you have checked the install the Qt sources options when running the installer, otherwise they will not be provided and you will run in to this problem. As an alternative, you can install the sources later using the SDK maintenance tool and then select Package manager > Miscellanous > Qt Sources.

Does Qt for Embedded Linux make any assumptions about keyboard and mouse events or can we use our own drivers?

Qt for Embedded Linux has a plug-in framework for mouse and keyboard drivers. Some drivers are already supported (linuxtp, intellimouse, mouseman, tslib etc.). Individual drivers can easily be written. Qt for Embedded Linux can also connect to kernel drivers for mouse and keyboard over sockets.


How can I change the row height of a QTreeView?

The delegate's sizeHint() http://doc.qt.io/qt-5/qstyleditemdelegate.html#sizeHint is used to determine the row height of the QTreeView, so you need to reimplement the delegate's sizeHint() http://doc.qt.io/qt-5/qstyleditemdelegate.html#sizeHint to return the size you want.

The following example illustrates how this can be done:

#include <QtGui>
 
class ItemDelegate : public QItemDelegate
{
public:
  ItemDelegate()
  {}
  QSize sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const
  {
    return QSize(50,50);
  }
};
int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  QTreeView view;
  QStandardItemModel *model = new QStandardItemModel;
  model->insertRows(0, 4);
  model->insertColumns(0, 4);
  for (int row = 0; row < 4; row++) {
    for (int col = 0; col < 4; col++) {
      QModelIndex index = model->index(row, col);
      model->setData(index, QVariant((row+1) *(col+1)).toString());
    }}
  ItemDelegate *delegate = new ItemDelegate();
  view.setModel(model);  
  view.setItemDelegate(delegate);
  view.show();
  return app.exec();
}

How can I avoid the underlining of links in a QTextBrowser ?

You can use style sheets for that. Here is an example:

#include <QtGui>
int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  QTextBrowser browser;
  QString sheet;
  sheet.append("a[href="qt4-2-intro.html"] { text-decoration: underline; font-
  style: italic; color: #00ff00; }");
  sheet.append("a { text-decoration: none; }");
  browser.document()->setDefaultStyleSheet(sheet);
  browser.setSource(QUrl("index.html"));
  browser.show();
  return app.exec();
}

If you start this example with 'index.html' taken from the Qt documentation all the links will have their underline removed (no text decoration) and the link that points to the Qt 4.2 Intro will be underlined, italic and show up in green

See also: http://www.w3.org/TR/CSS21/selector.html

for the list of supported CSS selectors.


Is it possible with Qt for Embedded Linux to maximize a window to full screen mode without any toolbars, scrollbars, menubars and the like?

Yes. This can this be done with Qt for Embedded Linux. It is also possible to expose a hidden toolbar at the top of the screen as one typically sees in these fullscreen modes.


What kind of touch screen / touch panel support does Qt for Embedded Linux have?

Qt for Embedded Linux supports several touch screen variants, including support for Linux Touch

Panel and tslib. Qt for Embedded Linux has a touch screen driver plug-in framework for implementing individual drivers.


How can I add tooltips to a QComboBox?

When setting tooltips for the individual items in a QComboBox http://doc.qt.io/qt-5/qcombobox.html you need to use the setItemData() http://doc.qt.io/qt-5/qcombobox.html#setItemData) function and specify the string you want to use for the tooltip specifying the ToolTipRole as the role for the data. For example:

#include <QtGui>
 
int main(int argc, char **argv)
{
  QApplication a(argc, argv);
  QComboBox box(0);
  box.addItem("Item One");
  box.setItemData(0, "This is a tooltip for item one", Qt::ToolTipRole);
  box.addItem("Item Two");
  box.setItemData(1, "This is a tooltip for item two", Qt::ToolTipRole);
  box.addItem("Item Thee");
  box.setItemData(2, "This is a tooltip for item three", Qt::ToolTipRole);
  box.show();
  return a.exec();
}

How can I translate the OK and Cancel buttons when using the static QMessageBox functions?

The OK and Cancel text for the buttons is part of the Qt source code. For more information on how to translate the Qt strings into your own language then look at lconvert. All you need to do is load the Qt translation file in addition to your original .qm file(s) when you load up your translation file(s). For the OK and Cancel buttons you would need to translate their text in the QDialogButtonBox section.

The example below demonstrates how this can be done:

TEMPLATE = app SOURCES += main.cpp TRANSLATIONS = t1_fr.ts qt_fr.ts CONFIG += console


#include <QtGui>
 
int main(int argc, char **argv)
{
    QApplication a(argc, argv);
    QTranslator trans(0);
    trans.load("t1_fr", ".");
    QTranslator trans2(0);
    trans2.load("qt_fr", ".");
    a.installTranslator(&trans);
    a.installTranslator(&trans2);
    QMessageBox::warning(0, QObject::tr("Warning Title"), 
                         QObject::tr("Warning Message"), 
                         QMessageBox::Ok|QMessageBox::Cancel);
    return a.exec();
}

Why doesn't Mac OS X respect carriage return?

On Mac OS X the idea of a new line is the same as on other unices. OS9 and below used carriage return. One decision we made with Qt was to follow the Unix convention on Mac OS X, therefore QTextStream (and Qt in general) does not know how to deal with carriage return. You should use new line instead.


How can I embed a widget with a titlebar inside a QGraphicsScene?

You can embed a widget with a titlebar inside a QGraphicsScene http://doc.qt.io/qt-5/latest/qgraphicsscene.html by specifying the Qt::Window http://doc.qt.io/qt-5/qt.html#WindowType-enum flag to the QGraphicsProxyWidget http://doc.qt.io/qt-5/latest/qgraphicsproxywidget.html or the QGraphicsWidget http://doc.qt.io/qt-5/latest/qgraphicswidget.html.

See the following example for an illustration:

#include <QtGui>
 
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
 
    QGraphicsScene scene;
#if 1  
   QGraphicsWidget *window = new QGraphicsWidget(0);
   window->setWindowFlags(Qt::Window);
   scene.addItem(window);
#else  
  QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget();
  proxy->setWidget(new QMainWindow());
  proxy->setWindowFlags(Qt::Window);
  scene.addItem(proxy);
#endif
    QGraphicsView view(&scene);
    view.resize(600, 600);
    view.show();
 
    return app.exec();
}

How can I detect hover events on the tabs of a QTabWidget?

The tabs in QTabBar http://doc.qt.io/qt-5/latest/qtabbar.html are not widgets per say, so it is not possible to get hold of them to check if they have received any events. Instead, you can check if the position of the event is positioned in the tab by using QTabBar::tabAt() http://doc.qt.io/qt-5/qtabbar.html#tabAt

The following example illustrates how this can be done:

#include <QtGui>
 
class TabWidget : public QTabWidget
{
public:
  TabWidget()
  {
    setMouseTracking(true);
    addTab(new QWidget(this), "first");
    addTab(new QWidget(this), "second");
    addTab(new QWidget(this), "third");
    tabBar()->setMouseTracking(true);
  }
  void mouseMoveEvent ( QMouseEvent * event )
  {
    QTabBar *wid = tabBar();
    if (wid && wid->tabAt(event->pos()) != -1)
      qDebug() << "mouse hovering in tab " << wid->tabAt(event->pos());
    return QTabWidget::mouseMoveEvent(event);
  }
};
 
int main(int argc, char** argv)
{
  QApplication app(argc, argv);
  TabWidget window;
  window.show();
  return app.exec();
}

Errors using macdeployqt caused by old version of XCode.

If macdeployqt fails with an error containing lines similar to the following :

Log: Using install_name_tool: 
Log: in calculator.app/Contents/Frameworks/QtGui.framework/Versions/4/QtGui 
Log: change reference QtCore.framework/Versions/4/QtCore 
Log: to @executable_path/../Frameworks/QtCore.framework/Versions/4/QtCore 
ERROR: install_name_tool: for architecture x86_64 object: calculator.app/Contents/Frameworks/QtGui.framework/Versions/4/QtGui malformed object (unknown load command 5)

The reason could be that you are using an older version of XCode.

We have found that upgrading XCode on these machines fixes this problem.


I would like to know how I can build Qt on Solaris / HP-UX / AIX

Note that Solaris 9 is currently not supported !

See our Supported Platforms http://doc.qt.io/qt-5/supported-platforms.html

You should be able to build Qt on those platforms if you disable WebKit and JavaScriptCore entirely. Those platforms are not supported and tested upstream, therefore Webkit is not supported on these.

If you use the -no-script and -no-webkit configure flags, then things should be fine. The legacy Qt script implementation is now available as an add-on solution. See:

http://blog.qt.io/2009/11/23/qtscript-in-46/


How can I have several Qt versions installed under WINNT\system32?

In order for your Qt applications to pick up the correct version of Qt installed under system32, you can build Qt with a custom name. You can do this using the qtlibinfix http://doc.qt.io/qt-5/latest/configure-options.html option i.e

configure -qtlibinfix customName

Then your different Qt applications should be able to pick up its custom Qt version from the system32 directory.


How can I set an empty default value in QSpinBox?

QSpinBox http://doc.qt.io/qt-5/latest/qspinbox.html does not allow displaying an empty value by default. Support for an empty value can be added however by reimplementing textFromValue() http://doc.qt.io/qt-5/latest/qspinbox.html#textFromValue and having it return an empty string under certain conditions. The example demonstrates this approach by returning the empty string instead of the minimum value.

#include <QtGui>
 
class SpinBox : public QSpinBox
{
  Q_OBJECT
public:
  SpinBox(QWidget *parent = 0)
    : QSpinBox(parent)
  {}
 
  virtual int valueFromText(const QString &text) const
  {
    if (text.isEmpty())
      return minimum();
    return QSpinBox::valueFromText(text);
  }
  virtual QString textFromValue(int v) const
  {
    if (v == minimum())
      return QString();
    return QSpinBox::textFromValue(v);
  }
};
 
#include "main.moc"
 
int main(int argc, char** argv)
{
  QApplication app(argc, argv);
  SpinBox box;
  box.show();
  return app.exec();
}

How can I use one horizontal scrollbar to scroll several QGraphicsViews?

In order to use one scrollbar to scroll several views, you can put your views and a QScrollBar http://doc.qt.io/qt-5/latest/qscrollbar.html inside a widget and connect the scrollbar's value changed signal to the setValue() http://doc.qt.io/qt-5/latest/qabstractslider.html#value-prop slots of the hidden horizontal scrollbars. In addition the ranges need to be kept in sync, although you can easily change this if you want to make it a bit smarter. See the following example for a demonstration:

#include <QtGui>
 
class Widget : public QWidget
{
    Q_OBJECT
public:
    Widget(QWidget *parent = 0) : QWidget(parent)
    {
        QGraphicsScene *scene = new QGraphicsScene();
        scene->addEllipse(QRectF(-100, -100, 300, 200), QPen(Qt::blue), QBrush(Qt::cyan));
 
        QGraphicsView *view1 = new QGraphicsView(scene);
        view1->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
 
        QGraphicsView *view2 = new QGraphicsView(scene);
        view2->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
 
        scrollbar = new QScrollBar(Qt::Horizontal, this);
        QVBoxLayout *vertical = new QVBoxLayout(this);
        QWidget *subWidget = new QWidget(this);
        QHBoxLayout *layout = new QHBoxLayout(subWidget);
        layout->addWidget(view1);
        layout->addWidget(view2);
 
        vertical->addWidget(subWidget);
        vertical->addWidget(scrollbar);
        scrollbar->setRange(view1->horizontalScrollBar()->minimum(), view1->horizontalScrollBar()->maximum());
 
        connect(scrollbar, SIGNAL(valueChanged(int)), view1->horizontalScrollBar(), SLOT(setValue(int)));
        connect(scrollbar, SIGNAL(valueChanged(int)), view2->horizontalScrollBar(), SLOT(setValue(int)));
        connect(view1->horizontalScrollBar(), SIGNAL(rangeChanged(int, int)), this, SLOT(updateRange(int, int)));
    }
public slots:
    void updateRange(int min, int max)
    {
        scrollbar->setRange(min, max);
    }
private:
    QScrollBar *scrollbar;
};
 
#include "main.moc"
 
int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    Widget widget;
    widget.show();
    return app.exec();
}

How can I get webkit to load local resources referenced within html returned from a custom scheme?

When creating a custom network manager in order to support a custom protocol then webkit does not know that the custom scheme should be considered as a local scheme. Therefore its default security mechanism of preventing access to local resources (file:) from remote schemes is triggered because it thinks the custom protocol is a remote scheme. Therefore images for example, which are referenced via local files will not get loaded. In order to get around this, you can call QWebSecurityOrigin::addLocalScheme() http://doc.qt.io/qt-5/qwebsecurityorigin.html#addLocalScheme which adds the given scheme to the list of schemes that are considered equivalent to the file scheme.



How can I get a QStackedWidget to automatically switch size depending on the content of the page?

When having a QStackedWidget http://doc.qt.io/qt-5/qstackedwidget.html that contains pages that you want to display in different sizes, then it can adjust its size automatically when switching pages if you follow these steps:

This article() http://doc.qt.io/qt-5/qq/qq06-qwidgetstack.html in Qt Quarterly demonstrates how this can be done. It is written for Qt 3, but the concept remains the same for Qt 4:

The example below illustrates how this can be done:

#include <QtGui>
class SubWidget : public QWidget
{
    Q_OBJECT
public:
    SubWidget(QWidget *parent) : QWidget(parent)
    {
        table = new QTableWidget(this);
        table->setColumnCount(10);
        table->setRowCount(10);
        QVBoxLayout *layout = new QVBoxLayout(this);
        layout->addWidget(table);
 
    }
    QSize minimumSizeHint () const
    {
        int newWidth = 0;
        int newHeight =0;
        for (int i = 0; i < table->columnCount(); i++) {
            newWidth+= table->columnWidth(i);
        }
        for (int y = 0; y < table->rowCount(); y++) {
            newHeight+= table->rowHeight(1);
        }
        newWidth+= table->verticalHeader()->width() + 2 *table->frameWidth();
        newHeight+= table->horizontalHeader()->height() +2 *table->frameWidth();
        return QSize(newWidth, newHeight);
    }
private:
    QTableWidget *table;
};
 
class Widget : public QWidget
{
    Q_OBJECT
public:
    Widget() : QWidget()
    {
        QPushButton *firstButton = new QPushButton("Open second page", this);
        QPushButton *secondButton = new QPushButton("Open first page", this);
        stackWidget = new QStackedWidget(this);
 
        SubWidget *firstPage = new SubWidget(stackWidget);
 
        QWidget *secondPage = new QWidget(stackWidget);
        QLineEdit *edit2 = new QLineEdit(secondPage);
        QVBoxLayout *secondPageLayout = new QVBoxLayout(secondPage);
        secondPageLayout->addWidget(edit2);
 
        stackWidget->addWidget(firstPage);
        stackWidget->addWidget(secondPage);
 
        QVBoxLayout *layout = new QVBoxLayout(this);
        layout->addWidget(secondButton);
        layout->addWidget(firstButton);
        layout->addWidget(stackWidget);
 
        connect(firstButton, SIGNAL(clicked()), this, SLOT(test1()));
        connect(secondButton, SIGNAL(clicked()), this, SLOT(test2()));
 
    }
    public slots:
        void test1()
        {
            changeCurrent(1);
        }
 
        void test2()
        {
            changeCurrent(0);
        }
private:
    void changeCurrent(int idx)
    {
        if (stackWidget->currentWidget() !=0) {
            stackWidget->currentWidget()->setSizePolicy(QSizePolicy::Ignored, 
                                                        QSizePolicy::Ignored);
        }
        stackWidget->setCurrentIndex(idx);
        stackWidget->currentWidget()->setSizePolicy(QSizePolicy::Expanding, 
                                                    QSizePolicy::Expanding);
        adjustSize();
    }
    QStackedWidget *stackWidget;
};
 
#include "main.moc"
 
int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    Widget window;
    window.show();
    return app.exec();
 
}

How can I modify the color of some of the rows in my QTableWidget ?

You can achieve this by reimplementing the delegate's paint() http://doc.qt.io/qt-5/qitemdelegate.html#paint function and then modifying the palette for the rows you want. See the following example:

#include <QtGui>
 
class ItemDelegate: public QItemDelegate
{
public:
  ItemDelegate()
  {
  }
 
  void paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const  
  {
    QPalette pal = option.palette;
    QStyleOptionViewItem  viewOption(option);
    if(index.row() == 0) {
      viewOption.palette.setColor(QPalette::HighlightedText, Qt::red);
    } else if (index.row() == 5) {
      viewOption.palette.setColor(QPalette::HighlightedText, Qt::blue);
    } else {
      viewOption.palette.setColor(QPalette::HighlightedText, Qt::white);
    }
    QItemDelegate::paint(painter, viewOption, index);
  }
 
 
};
 
int main(int argc, char** argv)
{
  QApplication app(argc, argv);
  QTableWidget table(10,10);
  table.setItemDelegate(new ItemDelegate());
  QTableWidgetItem *item1= new QTableWidgetItem();
  item1->setText("item 1");
  table.setItem(0, 0, item1);
  table.show();
  return app.exec();
}



How can I get hold of a cell widget's row?

The widgets set on the cells have nothing to do with the contents of the table, so calling currentRow() http://doc.qt.io/qt-5/latest/qtablewidget.html#currentRow will return -1 when such cells are being edited. In order to get row or column information for a cell widget that is being edited, you can get hold of the widget using QApplication::focusWidget() http://doc.qt.io/qt-5/latest/qapplication.html#focusWidget and get the model index using QTableView::indexAt() http://doc.qt.io/qt-5/latest/qtableview.html#indexAt. Then it is easy to get the row or column information from the model index by calling row() http://doc.qt.io/qt-5/qmodelindex.html#row or column() http://doc.qt.io/qt-5/latest/qmodelindex.html#column on it.

The following example illustrates how this can be done:

#include <QtGui>
 
class TableWidget : public QTableWidget
{
  Q_OBJECT
public:
  TableWidget()
  {
    edit = new QLineEdit(this);
    setColumnCount(5);
    setRowCount(5);
    setCellWidget(4,1, edit);
    connect(edit, SIGNAL(textChanged(const QString)), this, SLOT(test1(const QString))); 
  }
public slots:
void test1(const QString &text)
{
  QWidget *wid = QApplication::focusWidget();
  if (wid) {
    QModelIndex index = indexAt(wid->pos());
    qDebug() << index.row();
  }
}
 
private:
  QLineEdit *edit;
 
};
 
#include "main.moc"
 
int main(int argc, char** argv)
{
  QApplication app(argc, argv);
  TableWidget window;
  window.show();
  return app.exec();
}

Loading a Sql driver from a customized location

By default the sql driver is loaded from a ��lugins��subfolder of a library path.

If you want to load a sql driver from your own location (like c:\MyApplicationFolder) then you need to use a QPluginLoader and cast the plugin to a QSqlDriverPlugin.

Following is an example of how to load an OCI driver:

QPluginLoader loader("C:\\MyApplicationFolder\\qsqloci4.dll");
QObject *plugin = loader.instance();
 
if (!plugin)
    return;
 
QSqlDriverPlugin *sqlPlugin  = qobject_cast<QSqlDriverPlugin *>(plugin);
 
if (!sqlPlugin ) {
    QMessageBox::warning(this, "SQL plugin", "Loading failed", QMessageBox::Ok);
    return;
}
 
QSqlDatabase db = QSqlDatabase::addDatabase(ociDriver->create("QOCI"));

How can I detect in the .pro file if I am compiling on a 32 bit or a 64 bit platform?

You can use QMAKE_HOST.arch for this. The QMAKE_HOST variable expresses host information about the machine running qmake and QMAKE_HOST.arch allows you to determine the target architecture. You can use it as follows:

win32-g++:contains(QMAKE_HOST.arch, x86_64):{
do something
}

How can I disable autoscroll when selecting a partially displayed column in a QTreeView?

When clicking on a partially displayed column in a QTreeView http://doc.qt.io/qt-5/latest/qtreeview.html, the view will scroll to display the complete content of the column. If you want to disable this behavior, then you can subclass your view and reimplement scrollTo() http://doc.qt.io/qt-5/qtreeview.html#scrollTo to reset the value of the horizontal scrollbar to the value it had before the scroll.

The following example demonstrates how this can be done:

#include <QtGui>
 
class TreeWidget : public QTreeWidget
{
public:
  TreeWidget()
  {
    QTreeWidgetItem *tmp = new QTreeWidgetItem(this);
    tmp->setText(0, tr("This is the very very first column"));
    tmp->setText(1, tr("This is the very very secondary column"));
 
    QTreeWidgetItem *item2 = new QTreeWidgetItem(this);
    item2->setText(0, tr("This is the very very first column"));
    item2->setText(1, tr("This is the very very second column"));
 
    QTreeWidgetItem *item3 = new QTreeWidgetItem(this);
    item3->setText(0, tr("This is the very very first column"));
    item3->setText(1, tr("This is the very very second column"));
 
    QTreeWidgetItem *item4 = new QTreeWidgetItem(this);
    item4->setText(0, tr("This is the very very first column"));
    item4->setText(1, tr("This is the very very second column"));
  }
  void scrollTo ( const QModelIndex & index, ScrollHint hint = EnsureVisible )  
  {
    int myValue = horizontalScrollBar()->value();
    QTreeWidget::scrollTo(index, hint);
    horizontalScrollBar()->setValue(myValue);
  }
 
};
int main(int argc, char **argv)
{
  QApplication app(argc, argv);
  TreeWidget box;
  box.setColumnCount(2);
  box.resize(150,200);
  box.show();
  return app.exec();    
}

Can Qt Assistant be modified and redistributed with my application?

Qt Assistant can be modified and redistributed with your application, however the only constraint is that you do not modify the About boxes in Qt Assistant. They must still be available in their existing locations and contain the same text. For further information, consult the LICENSE file distributed with the package.

Note that you cannot distribute any of the documentation provided with Qt, this includes the Qt Assistant documentation, so you will need to provide your own if you want to provide documentation on how to use Qt Assistant.


How can I drag from e.g a QListWidget and drop in an editable QTableView?

In order to enable dragging from the QListWidget, you need to reimplement dragEnterEvent() http://doc.qt.io/qt-5/qabstractitemview.html#dragEnterEvent and dragMoveEvent() http://doc.qt.io/qt-5/qabstractitemview.html#dragMoveEvent to accept the event. In addition you need to set setDragEnabled() http://doc.qt.io/qt-5/qabstractitemview.html#dragEnabled-prop to true to enable dragging of the view's items.

For the QTableView you need to set setAcceptDrops() http://doc.qt.io/qt-5/qwidget.html#acceptDrops-prop to true in order to allow drops and then set a model on the view that has reimplemented setData() http://doc.qt.io/qt-5/qabstractitemmodel.html#setData and flags() http://doc.qt.io/qt-5/qabstractitemmodel.html#flags to allow editing of the model.

The example below illustrates how this can be implemented:

#include <QtCore> 
 
class ListWidget : public QListWidget 
{ 
public:
    ListWidget(QWidget *parent); 
protected: 
    void dragEnterEvent(QDragEnterEvent *e) 
    { 
        e->accept(); 
    } 
 
    void dragMoveEvent(QDragMoveEvent *e) 
    { 
        e->accept(); 
    } 
};
 
ListWidget::ListWidget(QWidget *parent) : QListWidget(parent) 
{
    addItem("Zero"); 
    addItem("First"); 
    addItem("Second"); 
    addItem("Third");
    addItem("Fourth"); 
    // The tree supports dragging of its own items
    setDragEnabled(true); 
} 
 
class DragModel : public QAbstractTableModel 
{ 
public:
    DragModel(QObject *parent) 
    { 
        QStringList firstRow; 
        QStringList secondRow; 
        for (int i = 0; i < 5; i++ ) { 
            firstRow.insert(i,"Row " + QString::number(i+1)); 
            secondRow.insert(i,"Row " + QString::number(i+1)); 
        }
        stringList << firstRow << secondRow; 
    } 
 
    // Returns the number of rows 
    int rowCount (const QModelIndex &parent = QModelIndex()) const 
    { 
        return 2; 
    } 
 
    // Returns the number of columns 
    int columnCount(const QModelIndex &parent = QModelIndex()) const 
    { 
        return 5; 
    } 
 
    // Returns an appropriate value for the requested data. 
    // If the view requests an invalid index or if the role is not 
    // Qt::DisplayRole, an invalid variant is returned. 
    // Any valid index that corresponds to a string for the index's column and row in 
    // the stringlist is returned 
    QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const 
    { 
        if (!index.isValid()) 
            return QVariant(); 
        if (role != Qt::DisplayRole) 
            return QVariant(); 
        QStringList list = (QStringList)stringList.at(index.row()); 
        return list.at(index.column()); 
    } 
 
    // Changes an item in the string list, but only if the following conditions 
    // are met: 
    // * The index supplied is valid. 
    // * The index corresponds to an item to be shown in a view. 
    // * The role associated with rendering data is specified. 
    // The dataChanged() signal is emitted if the item is changed. 
    bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) 
    { 
        if (index.isValid() && role == Qt::EditRole) { 
            // Set the data in the current cell to be value
            stringList[index.row()].replace(index.column(), value.toString()); 
            // We only want to change the data for the current cell 
            emit dataChanged(index, index);
            return true; 
        } 
        return true; 
    } 
 
    // Return the default flags for this index in addition to flags 
    // that will accept drops and editing 
    Qt::ItemFlags flags(const QModelIndex & index) const 
    { 
        return QAbstractItemModel::flags(index) | Qt::ItemIsDropEnabled | Qt::ItemIsEditable;
    } 
 
private: 
    // Each row will consist of a list of strings
    QList<QStringList> stringList; 
}; 
 
int main(int argc, char **argv) 
{
    QApplication app(argc, argv); 
    QWidget widget; 
    QHBoxLayout *layout = new QHBoxLayout(&widget); 
    ListWidget *listWidget = new ListWidget(&widget);
    QTableView *tableView = new QTableView(&widget); 
    DragModel *model = new DragModel(tableView); 
    tableView->setModel(model); 
    // The table view can accept drops 
    tableView->setAcceptDrops(true); 
    layout->addWidget(listWidget);
    layout->addWidget(tableView); 
    widget.show(); 
    return app.exec(); 
}

How can I build 64 bit Qt on a 32 bit system ?

If you want to build Qt as 64 bit, then you will first have to build the tools that Qt uses as 32 bit then the rest of the Qt libraries can be built in 64bit mode to enable you to build a 64bit version of your application.

The following steps should build everything correctly (using 32bit cp to signify a 32bit Visual Studio command prompt and 64bit cp to signify a 64bit Visual Studio command prompt):

  • 32bit cp: Run configure with the options you want
  • 32bit cp: cd src\tools && nmake (note this will fail at the uic3 step, this is fine)
  • 64bit cp: cd src && nmake (note this will fail at the uic3 step, again this is fine)
  • 64bit cp: cd src\tools\uic3 && qmake
  • 64bit cp: cd src && nmake

Bear in mind that this means you cannot use uic3 as part of your build process because of the fact it links against a 64bit library. Also note that you will not be able to run any of the applications you create with the 64 bit built Qt. You will have to deploy them to a 64 bit machine to run them.


How can I convert a QString to char* and vice versa?

In order to convert a QString http://doc.qt.io/qt-5/latest/qstring.html to a char*, then you first need to get a local8Bit representation of the string by calling toLocal8Bit() http://doc.qt.io/qt-5/qstring.html#toLocal8Bit on it which will return a QByteArray http://doc.qt.io/qt-5/latest/qbytearray.html. Then call data() http://doc.qt.io/qt-5/qbytearray.html#data on the QByteArray to get a pointer to the data stored in the byte array.

See the following example for a demonstration:

    int main(int argc, char **argv)
    {
     QApplication app(argc, argv);
      QString str1 = "Test";
      QByteArray ba = str1.toLocal8Bit();
      const char *c_str2 = ba.data();
      printf("str2: %s", c_str2);
      return app.exec();
    }

Note that it is necessary to store the bytearray before you call data() on it, a call like the following

const char *c_str2 = str2.toLocal8Bit().data();

will make the application crash as the QByteArray has not been stored and hence no longer exists

To convert a char* to a QString you can use the QString constructor that takes a QLatin1String http://doc.qt.io/qt-5/latest/qlatin1string.html to ensure the locale encoded string is correct with fromLocal8Bit() http://doc.qt.io/qt-5/qstring.html#fromLocal8Bit, e.g:

QString string = QString(QLatin1String(c_str2));
QString string = QString::fromLocal8Bit(c_str2);

In addition, if you want to just print out the string then you can use qPrintable() http://doc.qt.io/qt-5/qtglobal.html#qPrintable as a quick means to do this without having to convert to a char *. For example:

printf("str2: %s", qPrintable(str1));


How can I programatically find out which rows/items are visible in my view ?

Qt does not support retrieving the actual visible items in the viewport, you will have to calculate this yourself by listening to the valueChanged() http://doc.qt.io/qt-5/qabstractslider.html#valueChanged signal of the scrollbar to get the topmost row/item.

To get the bottom row, you can pass in the height of the view to QHeaderView::visualIndexAt() http://doc.qt.io/qt-5/qheaderview.html#visualIndexAt.

Qt supports two ways of scrolling, a pixel-based way and also an item-based way. Using the item-based http://doc.qt.io/qt-5/qabstractitemview.html#ScrollMode-enum way will make the calculation easier.

The following example demonstrates how this can be done:

#include <QtGui>
 
class TableWidget : public QTableWidget
{
    Q_OBJECT
public:
    TableWidget() : QTableWidget()
    {
        setColumnCount(100);
        setRowCount(100);
        setHorizontalScrollMode(QAbstractItemView::ScrollPerItem);
        setVerticalScrollMode(QAbstractItemView::ScrollPerItem);
        connect(horizontalScrollBar(), SIGNAL(valueChanged(int)), 
                this, SLOT(outputColumns(int)));
        connect(verticalScrollBar(), SIGNAL(valueChanged(int)), 
                this, SLOT(outputRows(int)));
    }
 
public slots:
    void outputColumns(int columns)
    {
        qDebug() << "Leftmost column" << columns;
        int right = horizontalHeader()->visualIndexAt(width());
        qDebug() << "Rightmost row" << right;
    }
    void outputRows(int rows)
    {
        qDebug() << "Top row" << rows;
        int left = verticalHeader()->visualIndexAt(height());
        qDebug() << "Bottom row" << left;
    }
};
 
#include "main.moc"
 
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    TableWidget table;
    table.show();
    return app.exec();
}

How do I create a sln from a SUBDIRS template?

All you need to do is:

  qmake -tp vc


on the pro file and it will create a solution file for you.


When setting a global color group on my Mac everything goes black. What is the problem?

The order of initialization of global objects is not defined, but in any case comes before any code in functions is executed. This means that the QColorGroup object you create is actually created before QApplication has been created, and since the QApplication constructor takes care of reading all the values from the system setting this creates an invalid color group, and potentially has nasty side effects (this largely depends on the compiler used).

You should avoid global objects of non POD-type (i.e. any type with a constructor).


How to minimize memory footprint in Qt for Embedded Linux?

There's no single magical step that can reduce the memory footprint, but there are several things you might wish to consider. One is the use of more aggressive optimization. The other is to use the following flags during configuration:

-no-stl 
-no-exceptions

To add the -o3 as a compiler option is pretty straightforward:

In the .pro file, add the following lines:

QMAKE_CFLAGS_DEBUG +=o3 
QMAKE_CXXFLAGS_DEBUG +=o3

You should use RELEASE instead of debug in your release version.

Also make sure you remove unnecessary options from your configuration. You should remove any features that you will not use in your final applications.


Who implements the antialiasing? You or the platform?

This depends on the engine:


  • PDF: antialiasing is done by the viewer


What function can I replace the QPaintDeivce::handle() function from Qt 3 in Qt 4 with?

In Qt 3 all of the paint devices were tied one-to-one with an underlying object. QPixmap http://doc.qt.io/qt-5/latest/qpixmap.html was a Windows HBITMAP or X11 pixmap for example. This tight connection between native and Qt classes no longer exists in Qt 4, but we have created mappings in the places where connections do exist. Toplevel widgets have a winId() http://doc.qt.io/qt-5/qwidget.html#winId for example and QPixmap a to/ fromWinHBITMAP() http://doc.qt.io/qt-5/qpixmap.html#fromWinHBITMAP, QWidget has getDc() http://doc.qt.io/qt-5/qwidget.html#getDC and releaseDC() http://doc.qt.io/qt-5/latest/qwidget.html#releaseDC etc.

So the new functions are spread over several classes and in most cases you could simply use one of the new alternatives. If you want to convert between Windows bitmaps and our pixmaps for example then you could use QPixmap::fromWinHBITMAP().

If you wish to use GDI directly on the widget then this is more tricky since all drawing happens in the backingstore, so you would also have to draw with GDI on it. That could be achieved in the paintEvent() http://doc.qt.io/qt-5/latest/qwidget.html#paintEvent by calling

painter.paintEngine()->getDC()

and then later releaseDC().


Why does the pushbutton suddenly become square on the Mac when it gets down to a certain size?

This is intentional and a compromise.The main idea is that at a certain size, the elliptical pushbuttons start looking very bad. We went with a bevel button because this was the best solution at the time, mainly because people are not constantly resizing their buttons and it preserves the font settings. If we were to use a mini button there we would have to change the widget's font and this would be disturbing, particularly for people who have a certain font set.


How can I keep the pixmap background at all times for flat buttons?

To keep the pixmap background all the time for flat buttons you need to set button's Button http://doc.qt.io/qt-5/qpalette.html#ColorRole-enum color role to be the pixmap. Note that changing the palette will not work for all styles, it will for example not work for the XP and MacStyle which are pixmap based. For these styles you will have to draw this yourself in the paint event or set a style that supports this on the button.

See the following example:

#include <QtGui>
 
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    app.setStyle(new QWindowsStyle());
    QPixmap pixmap(200, 200);
    {
        QPainter p(&pixmap);
        p.fillRect(0, 0, 200, 200, QRadialGradient(100, 100, 100, 150, 150));
    }
    QWidget wid;
    QPushButton *button = new QPushButton(&wid);
    button->setText("Button");
    button->setAutoFillBackground(true);
    button->setFlat(true);
    QPalette pal = button->palette();
    pal.setBrush(button->backgroundRole(), pixmap);
    pal.setBrush(QPalette::Button, pixmap);
    button->setPalette(pal);
 
    QVBoxLayout *layout = new QVBoxLayout(&wid);
    layout->addWidget(button);
    wid.show();
 
    int ret = app.exec();
    return ret;
}

How can I get rid of the focus rectangle for a QTextEdit in the motif style?

In order to get rid of the focus rectangle of a text edit, you need to subclass the QMotifStyle http://doc.qt.io/qt-5/latest/qmotifstyle.html and reimplement drawControl() http://doc.qt.io/qt-5/latest/qmotifstyle.html#drawControl to draw nothing when the control element is CE_FocusFrame http://doc.qt.io/qt-5/latest/qstyle.html#ControlElement-enum.

The example below demonstrates how this can be done.

    #include <QtGui>
 
   class Style : public QMotifStyle
   {
    public:
            Style()
            {
            }
 
           void drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget = 0) const
            {
                   if (element == CE_FocusFrame)
                          return;
                   QMotifStyle::drawControl(element, option, painter, widget);
            }
   };
 
    int main(int argc, char **argv)
    {
        QApplication app(argc, argv);
 
           Style *s = new Style();
            app.setStyle(s);
 
           QWidget wid;
            QPushButton *button = new QPushButton("text", &wid);
            QTextEdit *edit = new QTextEdit(&wid);
 
           QVBoxLayout *layout = new QVBoxLayout(&wid);
            layout->addWidget(button);
            layout->addWidget(edit);
 
        wid.show();
        return app.exec();
    }

Can I resize a toplevel window to zero height and zero width?

This will depend upon the different window managers. Windows for example enforces your top level windows to have a minimum size, so it is not possible to resize them smaller than that size using Qt. Other window managers may allow this though, if you have given your window a minimumSizeHint() http://doc.qt.io/qt-5/latest/qwidget.html#minimumSizeHint-prop of 0,0.


After installing a new Qt version, Designer crashes when it loads the plugins, what's wrong?

If you have had an earlier version of Qt installed, then it might be that your plugins have not been updated to the new Qt version. Go into the designer\plugins directory and rebuild all your Designer plugins and if you have created additional plugins then rebuild them too.


How can I easily create a Visual Studio project from my existing pro file

Simply run qmake as follows:

    • qmake -tp vc**

Note that this will take the existing template setting and prepend vc to it, so it will create a valid Visual Studio project file regardless of the template you use. The only exception is the SUBDIRS template.


Is there a way to tell qmake to copy files into my application bundle (e.g. private frameworks, sound files, etc.)?

You can do this using QMAKE_BUNDLE_DATA. All you need to do is define your files and where you want to put them in the bundle. qmake will take care of the rest.

Here's an example where we add a framework to the bundle

# Rest of the .pro file
PRIVATE_FRAMEWORKS.files = /path/to/MyFramework.framework
PRIVATE_FRAMEWORKS.path = Contents/Frameworks
QMAKE_BUNDLE_DATA += PRIVATE_FRAMEWORKS


Which UML modelers can be used to perform reverse engineering on code written with Qt?

Qt does not provide a tool to help you with reverse engineering, but you can use Rational Rose, see:

http://www-306.ibm.com/software/awdtools/developer/technical/

Alternatively, you can use Umbrello from KDE, see:

http://uml.sourceforge.net/index.php


How does Qt pick a font for the application?

If you have not set a font for your application then the default font on your machine will be used, and the default font can be different on different machines. On Windows the default Windows font is used, on X11 the one in qtrc can be used. If a default font can't be found, then a font specified by Qt will be used.

In order to get the same font for all machines you should set a font for your application. Note that this font needs to be installed on the target machine. You can find information on this subject here:

http://doc.qt.io/qt-5/qfont.html


How can I make one of my toolbars appear on the right hand side of the topdock area?

There is no API for this, but you can play around with the size policies http://doc.qt.io/qt-5/qsizepolicy.html#Policy-enum to achieve what you want. See the following example:

#include <QtGui>
 
int main(int argc, char **argv)
{
	QApplication app(argc, argv);
	QMainWindow box;
	QToolBar *toolBar = new QToolBar(&box);
	QToolBar *toolBar2 = new QToolBar(&box);
 
	toolBar->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
	box.addToolBar(toolBar);
	box.addToolBar(toolBar2);
 
	QAction *action = toolBar->addAction(one);
	QAction *action2 = toolBar2->addAction(right);
	box.show();
	return app.exec();
}



My custom widget appears as a grey rectangle in Designer. How can I fix this ?

The reason you only see a grey rectangle on the form is probably that you have not reimplemented domXml() http://doc.qt.io/qt-5/latest/qdesignercustomwidgetinterface.html#domXml. You need to reimplement domXml() to at least specify the geometry property. See the following code for an example:

QString MyWidgetPlugin::domXml() const
{
    return QString("<widget class=&#92;"MyWidget&#92;" name=&#92;"MyWidget&#92;"> "
                   " <property name=&#92;"geometry&#92;"> "
                   " <rect> "
                   " <x>0</x> "
                   " <y>0</y> "
                   " <width>100</width> "
                   " <height>100</height> "
                   " </rect> "
                   " </property> "
                   " </widget>");
}

See the documentation:

http://doc.qt.io/qt-5/qdesignercustomwidgetinterface.html#domXml


How can I run multiple instances of an application on Mac OS X ?

By default LaunchServices tries to make sure only one application is running at the time, but you can use QProcess to start others. See the documentation:

http://doc.qt.io/qt-5/qprocess.html#start

If you want to run multiple instances yourself, you can go into the bundle and type the name of the executable with an & at the end, this will allow you to open new instances.


Can I use your icons in my product?

The icons that are used in Qt's tools, i.e. Qt Designer http://doc.qt.io/qt-5/latest/designer-manual.html, Qt Linguist http://doc.qt.io/qt-5/latest/linguist-manual.html and Qt Assistant http://doc.qt.io/qt-5/latest/assistant-manual.html are designed specifically by us. You have permission to use these in your own application, but you will need to add a notice that indicates that the copyright of the icons belong to The Qt Company.


How can I represent rich text in an itemview ?

The default delegate does not process or interpret HTML tags. The representation of the displayed information is handled at a very low level in the QAbstractItemDelegate http://doc.qt.io/qt-5/latest/qabstractitemdelegate.html.

You could choose to implement this in a custom delegate, and then handle this in the QAbstractItemDelegate::paint() http://doc.qt.io/qt-5/latest/qabstractitemdelegate.html#paint method. The example which illustrates this best is under ./examples/itemviews/pixelator http://doc.qt.io/qt-5/latest/itemviews-pixelator.html in your Qt directory.

An alternative approach which is only feasible for small applications, is to actually set a style sheet on supported widgets on the QTableView http://doc.qt.io/qt-5/latest/qtableview.html cells and style them accordingly.


How can I lay out a splitter so that one widget takes 2/3 of the space and another 1/3?

You can use QSplitter::setSizes() http://doc.qt.io/qt-5/qsplitter.html#setSizes for this.



QTextEdit gets a performance problem when filling up

QTextEdit http://doc.qt.io/qt-5/latest/qtextedit.html is optimized for working with paragraphs and it is not designed for handling very large paragraphs. When having very long paragraphs you will run into a performance problem at some point, when this will happen depends on the speed of your machine, the font you are using etc. We are not planning to change this design since the users generally split their documents into paragraphs.

A solution to this problem can be to use a QPlainTextEdit http://doc.qt.io/qt-5/latest/qplaintextedit.html instead of a QTextedit and set the maximum number of blocks using setMaximumBlockCount() http://doc.qt.io/qt-5/qplaintextedit.html#maximumBlockCount-prop.



Why doesn't OpenGL improve the performance of the chip demo?

The chip demo (as are most of the demos included with Qt) favors the raster engine since it draws many small shapes with minor state changes.

The GL engines are better at drawing larger shapes with gradients and alpha etc.

Too many small shapes and it suffers from overhead in the GL calls.

Whether or not OpenGL improves performance is down to the scenario in which you use it, but in most cases it is better. It just isn't for widget drawing nor for many of the Qt examples. If you had a picture gallery it would show off the performance improvements that OpenGL can bring.


How can I get rid of the white space outside the cells of my table?

If you don't need all of your header sections to be resizable, then you can achieve this by setting the resizeMode http://doc.qt.io/qt-5/qheaderview.html#ResizeMode-enum to stretch for one or more of the header sections:

table->horizontalHeader()->setResizeMode(4, QHeaderView::Stretch);

If you do need all of your header sections to be resizeable, then you need to reimplement the sizeHint() http://doc.qt.io/qt-5/qwidget.html#sizeHint-prop to account for the size of the cells and headers in the table.

Then you need to set this size to be the maximum size of the table. Since you allow resizing of the table's columns, you also need to connect a slot to the sectionResized http://doc.qt.io/qt-5/latest/qheaderview.html#sectionResized signal and call setMaximumSize(sizeHint()) in there.

The example below demonstrates how this can be done for a toplevel table. If you need this to work for a table that is embedded into another widget, then you need to set the sizePolicy http://doc.qt.io/qt-5/latest/qsizepolicy.html#Policy-enum to fixed, so that the sizeHint() is the only alternative.

    #include <QtGui>
 
    class TableWidget : public QTableWidget
    {
     Q_OBJECT
    public:
     TableWidget(int rows, int columns) : QTableWidget(rows, columns)
     {
      connect(horizontalHeader(), SIGNAL(sectionResized(int, int, int)), this, SLOT(sectionResized()));
      connect(verticalHeader(), SIGNAL(sectionResized(int, int, int)), this, SLOT(sectionResized()));
     }
 
     QSize sizeHint () const
     {
      int newWidth = 0;
      int newHeight =0;
      for (int i = 0; i