Home · All Classes · Modules |
The QObject class is the base class of all Qt objects. More..
The QGraphicsTransform class is an abstract base class for building advanced transformations on QGraphicsItems. As an alternative to QGraphicsItem::transform, QGraphicsTransform lets you create and control advanced transformations that can be configured independently using specialized properties. Make sure the QOBJECT macro is present in the definition of all QObject-derived classes. Make sure you declare your QObject-derived classes in your header files ONLY. Make sure all of your header files are listed in your.pro file in the HEADERS= list. Run qmake every time you add QOBJECT to one of your classes or modify your.pro file.
Inherited by AbstractAudioOutput, Notifier, Effect, MediaController, MediaObject, QAbstractAnimation, QAbstractEventDispatcher, QAbstractItemDelegate, QAbstractItemModel, QAbstractMessageHandler, QAbstractNetworkCache, QAbstractState, QAbstractTextDocumentLayout, QAbstractTransition, QAbstractUriResolver, QAbstractVideoSurface, QAction, QActionGroup, QAssistantClient, QAudioInput, QAudioOutput, QButtonGroup, QClipboard, QCompleter, QCoreApplication, QDataWidgetMapper, QDBusAbstractAdaptor, QDBusAbstractInterface, QDBusPendingCallWatcher, QDBusServiceWatcher, QDeclarativeComponent, QDeclarativeContext, QDeclarativeEngine, QDeclarativeExpression, QDeclarativeExtensionPlugin, QDeclarativePropertyMap, QDesignerFormEditorInterface, QDesignerFormWindowManagerInterface, QDrag, QEventLoop, QExtensionFactory, QExtensionManager, QFileSystemWatcher, QFtp, QGesture, QGLShader, QGLShaderProgram, QGraphicsAnchor, QGraphicsEffect, QGraphicsItemAnimation, QGraphicsObject, QGraphicsScene, QGraphicsTransform, QHelpEngineCore, QHelpSearchEngine, QHttp, QHttpMultiPart, QInputContext, QIODevice, QItemSelectionModel, QLayout, QLibrary, QLocalServer, QMimeData, QMovie, QNetworkAccessManager, QNetworkConfigurationManager, QNetworkCookieJar, QNetworkSession, QObjectCleanupHandler, QPluginLoader, QPyDeclarativePropertyValueSource, QPyDesignerContainerExtension, QPyDesignerCustomWidgetCollectionPlugin, QPyDesignerCustomWidgetPlugin, QPyDesignerMemberSheetExtension, QPyDesignerPropertySheetExtension, QPyDesignerTaskMenuExtension, QPyTextObject, QScriptEngine, QScriptEngineDebugger, QSessionManager, QSettings, QSharedMemory, QShortcut, QSignalMapper, QSocketNotifier, QSound, QSqlDriver, QStyle, QSvgRenderer, QSyntaxHighlighter, QSystemTrayIcon, QTcpServer, QTextDocument, QTextObject, QThread, QThreadPool, QTimeLine, QTimer, QTranslator, QUndoGroup, QUndoStack, QValidator, QWebFrame, QWebHistoryInterface, QWebPage, QWebPluginFactory and QWidget.
Methods
- bool blockSignals (self, bool b)
- list-of-QObject children (self)
- bool connect (self, QObject, SIGNAL(), SLOT(), Qt.ConnectionType = Qt.AutoConnection)
- customEvent (self, QEvent)
- disconnectNotify (self, SIGNAL() signal)
- dumpObjectTree (self)
- emit (self, SIGNAL(), ..)
- bool eventFilter (self, QObject, QEvent)
- QObject findChild (self, type type, QString name = QString())
- QObject findChild (self, tuple types, QString name = QString())
- list-of-QObject findChildren (self, type type, QString name = QString())
- list-of-QObject findChildren (self, tuple types, QString name = QString())
- list-of-QObject findChildren (self, type type, QRegExp regExp)
- list-of-QObject findChildren (self, tuple types, QRegExp regExp)
- installEventFilter (self, QObject)
- killTimer (self, int id)
- moveToThread (self, QThread thread)
- QObject parent (self)
- pyqtConfigure (self, object)
- removeEventFilter (self, QObject)
- int senderSignalIndex (self)
- setParent (self, QObject)
- bool signalsBlocked (self)
- QThread thread (self)
- QString tr (self, str sourceText, str disambiguation = None, int n = -1)
- QString trUtf8 (self, str sourceText, str disambiguation = None, int n = -1)
Static Methods
- bool connect (QObject, SIGNAL(), QObject, SLOT(), Qt.ConnectionType = Qt.AutoConnection)
- bool connect (QObject, SIGNAL(), callable, Qt.ConnectionType = Qt.AutoConnection)
- bool disconnect (QObject, SIGNAL(), QObject, SLOT())
Special Methods
- object __getattr__ (self, str name)
Qt Signals
Static Members
- QMetaObject staticMetaObject
Detailed Description
The QObject class is the base class of all Qt objects.
QObject is the heart of the Qt ObjectModel. The central feature in this model is a very powerfulmechanism for seamless object communication called signals and slots. Youcan connect a signal to a slot with connect() and destroy the connectionwith disconnect(). To avoidnever ending notification loops you can temporarily block signalswith blockSignals(). Theprotected functions connectNotify() and disconnectNotify() make itpossible to track connections.
QObjects organizethemselves in object trees. When youcreate a QObject with another object as parent, the object willautomatically add itself to the parent's children() list. The parent takesownership of the object; i.e., it will automatically delete itschildren in its destructor. You can look for an object by name andoptionally type using findChild() or findChildren().
Every object has an objectName() and its class namecan be found via the corresponding metaObject() (see QMetaObject.className()). You candetermine whether the object's class inherits another class in theQObject inheritance hierarchy by using the inherits() function.
When an object is deleted, it emits a destroyed() signal. You can catch thissignal to avoid dangling references to QObjects.
QObjects can receiveevents through event() and filterthe events of other objects. See installEventFilter() andeventFilter() for details. Aconvenience handler, childEvent(), can be reimplemented tocatch child events.
Last but not least, QObject provides the basic timer support inQt; see QTimer for high-level support fortimers.
Notice that the Q_OBJECTmacro is mandatory for any object that implements signals, slots orproperties. You also need to run the MetaObject Compiler on the source file. We strongly recommend theuse of this macro in all subclasses of QObject regardless ofwhether or not they actually use signals, slots and properties,since failure to do so may lead certain functions to exhibitstrange behavior.
All Qt widgets inherit QObject. The convenience functionisWidgetType() returnswhether an object is actually a widget. It is much faster thanqobject_cast(obj) orobj->inherits('QWidget').
Some QObject functions, e.g. children(), return a QObjectList. QObjectList is a typedef forQList.
Thread Affinity
A QObject instance is said to have a thread affinity, orthat it lives in a certain thread. When a QObject receives aqueued signal or aposted event,the slot or event handler will run in the thread that the objectlives in.
Note: If a QObject has no thread affinity (that is, ifthread() returns zero), or if itlives in a thread that has no running event loop, then it cannotreceive queued signals or posted events.
By default, a QObject lives in the thread in which it iscreated. An object's thread affinity can be queried using thread() and changed using moveToThread().
All QObjects mustlive in the same thread as their parent. Consequently:
li
setParent() will fail if the twoQObjects involved livein different threads. li
Whena QObject is moved to another thread, all its children will beautomatically moved too. li
moveToThread() will fail ifthe QObject has a parent. li
If QObjects are created within QThread.run(), they cannot become childrenof the QThread object because theQThread does not live in the thread thatcalls QThread.run().
Note: A QObject's member variables do notautomatically become its children. The parent-child relationshipmust be set by either passing a pointer to the child's constructor, or by calling setParent(). Without this step, theobject's member variables will remain in the old thread whenmoveToThread() iscalled.
No copy constructor or assignment operator
QObject has neither a copy constructor nor an assignmentoperator. This is by design. Actually, they are declared, but in aprivate section with the macro Q_DISABLE_COPY(). In fact, all Qtclasses derived from QObject (direct or indirect) use this macro todeclare their copy constructor and assignment operator to beprivate. The reasoning is found in the discussion on Identity vs Value on the QtObject Model page.
The main consequence is that you should use pointers to QObject(or to your QObject subclass) where you might otherwise be temptedto use your QObject subclass as a value. For example, without acopy constructor, you can't use a subclass of QObject as the valueto be stored in one of the container classes. You must storepointers.
Auto-Connection
Does it matter which memory slot i use imac computers. Qt's meta-object system provides a mechanism to automaticallyconnect signals and slots between QObject subclasses and theirchildren. As long as objects are defined with suitable objectnames, and slots follow a simple naming convention, this connectioncan be performed at run-time by the QMetaObject.connectSlotsByName()function.
uic generates code that invokes thisfunction to enable auto-connection to be performed between widgetson forms created with Qt Designer. More information aboutusing auto-connection with Qt Designer is given in theUsing a Designer UI File inYour Application section of the Qt Designer manual.
Dynamic Properties
From Qt 4.2, dynamic properties can be added to and removed fromQObject instances at run-time. Dynamic properties do not need to bedeclared at compile-time, yet they provide the same advantages asstatic properties and are manipulated using the same API - usingproperty() to read them andsetProperty() to writethem.
From Qt 4.3, dynamic properties are supported by Qt Designer,and both standard Qt widgets and user-created forms can be givendynamic properties.
Internationalization (i18n)
All QObject subclasses support Qt's translation features, makingit possible to translate an application's user interface intodifferent languages.
To make user-visible text translatable, it must be wrapped incalls to the tr() function. This isexplained in detail in the Writing Source Code forTranslation document.
Method Documentation
QObject.__init__ (self, QObjectparent = None)
The parent argument, if not None, causes self to be owned by Qt instead of PyQt.
Constructs an object with parent object parent.
The parent of an object may be viewed as the object's owner. Forinstance, a dialog box is the parent ofthe OK and Cancel buttons it contains.
The destructor of a parent object destroys all childobjects.
Setting parent to 0 constructs an object with no parent.If the object is a widget, it will become a top-level window.
See alsoparent(),findChild(), and findChildren().
bool QObject.blockSignals (self, bool b)
The return value is the previous value of signalsBlocked().
Note that the destroyed()signal will be emitted even if the signals for this object havebeen blocked.
See alsosignalsBlocked().
QObject.childEvent (self, QChildEvent)
This event handler can be reimplemented in a subclass to receivechild events. The event is passed in the eventparameter.
QEvent.ChildAdded andQEvent.ChildRemoved events aresent to objects when children are added or removed. In both casesyou can only rely on the child being a QObject, or if isWidgetType() returns true, aQWidget. (This is because, in theChildAdded case, the child isnot yet fully constructed, and in the ChildRemoved case it might have beendestructed already).
QEvent.ChildPolished eventsare sent to widgets when children are polished, or when polishedchildren are added. If you receive a child polished event, thechild's construction is usually completed. However, this is notguaranteed, and multiple polish events may be delivered during theexecution of a widget's constructor.
For every child widget, you receive one ChildAdded event, zero or more ChildPolished events, and one ChildRemoved event.
The ChildPolished event isomitted if a child is removed immediately after it is added. If achild is polished several times during construction anddestruction, you may receive several child polished events for thesame child, each time with a different virtual table.
See alsoevent().
list-of-QObject QObject.children (self)
Returns a list of child objects. The QObjectList class is definedin the header file as the following:
The first child added is the first object in the list and the last childadded is the last object in the list,i.e. new children are appended at the end.
Note that the list order changes when QWidget children are raised or lowered. A widget that is raised becomesthe last object in the list, and a widget that is lowered becomesthe first object in the list.
See alsofindChild(), findChildren(), parent(), and setParent().
bool QObject.connect (QObject, SIGNAL(), QObject, SLOT(), Qt.ConnectionType = Qt.AutoConnection)
Creates a connection of the given type from thesignal in the sender object to the method inthe receiver object. Returns true if the connectionsucceeds; otherwise returns false.
You must use the SIGNAL() and SLOT() macroswhen specifying the signal and the method, forexample:
This example ensures that the label always displays the currentscroll bar value. Note that the signal and slots parameters mustnot contain any variable names, only the type. E.g. the followingwould not work and return false:
A signal can also be connected to another signal:
In this example, the MyWidget constructor relays asignal from a private member variable, and makes it available undera name that relates to MyWidget.
A signal can be connected to many slots and signals. Manysignals can be connected to one slot.
If a signal is connected to several slots, the slots areactivated in the same order as the order the connection was made,when the signal is emitted.
The function returns true if it successfully connects the signalto the slot. It will return false if it cannot create theconnection, for example, if QObject isunable to verify the existence of either signal ormethod, or if their signatures aren't compatible.
By default, a signal is emitted for every connection you make;two signals are emitted for duplicate connections. You can breakall of these connections with a single disconnect() call. If you pass theQt.UniqueConnectiontype, the connection will only be made if it is not aduplicate. If there is already a duplicate (exact same signal tothe exact same slot on the same objects), the connection will failand connect will return false.
The optional type parameter describes the type ofconnection to establish. In particular, it determines whether aparticular signal is delivered to a slot immediately or queued fordelivery at a later time. If the signal is queued, the parametersmust be of types that are known to Qt's meta-object system, becauseQt needs to copy the arguments to store them in an event behind thescenes. If you try to use a queued connection and get the errormessage
call qRegisterMetaType() toregister the data type before you establish the connection.
Note: This function is thread-safe.
See alsodisconnect(), sender(), qRegisterMetaType(), andQ_DECLARE_METATYPE().
bool QObject.connect (QObject, SIGNAL(), callable, Qt.ConnectionType = Qt.AutoConnection)
Creates a connection of the given type from thesignal in the sender object to the method inthe receiver object. Returns true if the connectionsucceeds; otherwise returns false.
This function works in the same way as connect(const QObject *sender, const char *signal, constQObject *receiver, const char *method,Qt.ConnectionType type)but it uses QMetaMethod to specifysignal and method.
This function was introduced in Qt 4.8.
See also connect(const QObject *sender, const char*signal, const QObject *receiver, const char *method,Qt.ConnectionType type).
bool QObject.connect (self, QObject, SIGNAL(), SLOT(), Qt.ConnectionType = Qt.AutoConnection)
This function overloads connect().
Connects signal from the sender object to thisobject's method.
Equivalent to connect(sender, signal,this, method, type).
Every connection you make emits a signal, so duplicateconnections emit two signals. You can break a connection usingdisconnect().
Note: This function is thread-safe.
See alsodisconnect().
QObject.connectNotify (self, SIGNAL() signal)
If you want to compare signal with a specific signal, useQLatin1String and theSIGNAL() macro as follows:
If the signal contains multiple parameters or parameters thatcontain spaces, call QMetaObject.normalizedSignature()on the result of the SIGNAL() macro.
Warning: This function violates the object-orientedprinciple of modularity. However, it might be useful when you needto perform expensive initialization only if something is connectedto a signal.
See alsoconnect() anddisconnectNotify().
QObject.customEvent (self, QEvent)
This event handler can be reimplemented in a subclass to receivecustom events. Custom events are user-defined events with a typevalue at least as large as the QEvent.User item of the QEvent.Type enum, and is typically aQEvent subclass. The event is passed inthe event parameter.
See alsoevent() andQEvent.
QObject.deleteLater (self)
The object will be deleted when control returns to the eventloop. If the event loop is not running when this function is called(e.g. deleteLater() is called on an object before QCoreApplication.exec()), theobject will be deleted once the event loop is started. IfdeleteLater() is called after the main event loop has stopped, theobject will not be deleted. Since Qt 4.8, if deleteLater() iscalled on an object that lives in a thread with no running eventloop, the object will be destroyed when the thread finishes.
Note that entering and leaving a new event loop (e.g., byopening a modal dialog) will not perform the deferreddeletion; for the object to be deleted, the control must return tothe event loop from which deleteLater() was called.
Note: It is safe to call this function more than once;when the first deferred deletion event is delivered, any pendingevents for the object are removed from the event queue.
See alsodestroyed()and QPointer.
bool QObject.disconnect (QObject, SIGNAL(), QObject, SLOT())
Disconnects signal in object sender frommethod in object receiver. Returns true if theconnection is successfully broken; otherwise returns false.
A signal-slot connection is removed when either of the objectsinvolved are destroyed.
disconnect() is typically used in three ways, as the followingexamples demonstrate.
- Disconnect everything connected to an object's signals:
equivalent to the non-static overloaded function
- Disconnect everything connected to a specific signal:
equivalent to the non-static overloaded function
- Disconnect a specific receiver:
equivalent to the non-static overloaded function
0 may be used as a wildcard, meaning 'any signal', 'anyreceiving object', or 'any slot in the receiving object',respectively.
The sender may never be 0. (You cannot disconnect signalsfrom more than one object in a single call.)
If signal is 0, it disconnects receiver andmethod from any signal. If not, only the specified signal isdisconnected.
If receiver is 0, it disconnects anything connected tosignal. If not, slots in objects other than receiverare not disconnected.
If method is 0, it disconnects anything that is connectedto receiver. If not, only slots named method will bedisconnected, and all other slots are left alone. The methodmust be 0 if receiver is left out, so you cannot disconnecta specifically-named slot on all objects.
Note: This function is thread-safe.
See alsoconnect().
bool QObject.disconnect (QObject, SIGNAL(), callable)
Disconnects signal in object sender frommethod in object receiver. Returns true if theconnection is successfully broken; otherwise returns false.
This function provides the same possibilities likedisconnect(const QObject *sender, constchar *signal, const QObject *receiver,const char *method) but uses QMetaMethod to represent the signal and themethod to be disconnected.
Additionally this function returnsfalse and no signals and slotsdisconnected if:
- signal is not a member of sender class or one of itsparent classes.
- method is not a member of receiver class or one of itsparent classes.
- signal instance represents not a signal.
QMetaMethod() may be used as wildcard in the meaning 'anysignal' or 'any slot in receiving object'. In the same way 0 can beused for receiver in the meaning 'any receiving object'. Inthis case method should also be QMetaMethod(). senderparameter should be never 0.
This function was introduced in Qt 4.8.
See also disconnect(const QObject *sender, const char*signal, const QObject *receiver, const char *method).
QObject.disconnectNotify (self, SIGNAL() signal)
See connectNotify() foran example of how to compare signal with a specificsignal.
Warning: This function violates the object-orientedprinciple of modularity. However, it might be useful for optimizingaccess to expensive resources.
See alsodisconnect() and connectNotify().
QObject.dumpObjectInfo (self)
See alsodumpObjectTree().
QObject.dumpObjectTree (self)
See alsodumpObjectInfo().
list-of-QByteArray QObject.dynamicPropertyNames (self)
Returns the names of all properties that were dynamically addedto the object using setProperty().
Qt No Such Slot In Derived Classroom
This function was introduced in Qt 4.2.
QObject.emit (self, SIGNAL(), ..)
bool QObject.event (self, QEvent)
This virtual function receives events to an object and shouldreturn true if the event e was recognized and processed.
The event() function can be reimplemented to customize thebehavior of an object.
See alsoinstallEventFilter(),timerEvent(), QApplication.sendEvent(),QApplication.postEvent(),and QWidget.event().
bool QObject.eventFilter (self, QObject, QEvent)
Filters events if this object has been installed as an eventfilter for the watched object.
In your reimplementation of this function, if you want to filterthe event out, i.e. stop it being handled further, returntrue; otherwise return false.
Example:
Notice in the example above that unhandled events are passed tothe base class's eventFilter() function, since the base class mighthave reimplemented eventFilter() for its own internal purposes.
Warning: If you delete the receiver object in thisfunction, be sure to return true. Otherwise, Qt will forward theevent to the deleted object and the program might crash.
See alsoinstallEventFilter().
QObject QObject.findChild (self, type type, QString name = QString())
If there is more than one child matching the search, the mostdirect ancestor is returned. If there are several direct ancestors,it is undefined which one will be returned. In that case, findChildren() should be used.
This example returns a child QPushButton of parentWidget named'button1':
This example returns a QListWidget child ofparentWidget:
See alsofindChildren().
QObject QObject.findChild (self, tuple types, QString name = QString())
list-of-QObject QObject.findChildren (self, type type, QString name = QString())
The following example shows how to find a list of child QWidgets of the specified parentWidgetnamed widgetname:
This example returns all QPushButtons that are childrenof parentWidget:
See alsofindChild().
list-of-QObject QObject.findChildren (self, tuple types, QString name = QString())
This function overloads findChildren().
Returns the children of this object that can be cast to type Tand that have names matching the regular expression regExp,or an empty list if there are no such objects. The search isperformed recursively.
list-of-QObject QObject.findChildren (self, type type, QRegExpregExp)
list-of-QObject QObject.findChildren (self, tuple types, QRegExpregExp)
bool QObject.inherits (self, str classname)
Returns true if this object is an instance of a class thatinherits className or a QObjectsubclass that inherits className; otherwise returnsfalse.
A class is considered to inherit itself.
Example:
If you need to determine whether an object is an instance of aparticular class for the purpose of casting it, consider usingqobject_cast(object) instead.
See alsometaObject() and qobject_cast().
QObject.installEventFilter (self, QObject)
Installs an event filter filterObj on this object. Forexample:
An event filter is an object that receives all events that aresent to this object. The filter can either stop the event orforward it to this object. The event filter filterObjreceives events via its eventFilter() function. The eventFilter() function must returntrue if the event should be filtered, (i.e. stopped); otherwise itmust return false.
If multiple event filters are installed on a single object, thefilter that was installed last is activated first.
Here's a KeyPressEater class that eats the key pressesof its monitored objects:
And here's how to install it on two widgets:
The QShortcut class, for example,uses this technique to intercept shortcut key presses.
Warning: If you delete the receiver object in youreventFilter() function, besure to return true. If you return false, Qt sends the event to thedeleted object and the program will crash.
Note that the filtering object must be in the same thread asthis object. If filterObj is in a different thread, thisfunction does nothing. If either filterObj or this objectare moved to a different thread after calling this function, theevent filter will not be called until both objects have the samethread affinity again (it is not removed).
See alsoremoveEventFilter(), eventFilter(), and event().
bool QObject.isWidgetType (self)
Calling this function is equivalent to callinginherits('QWidget'), except that it ismuch faster.
QObject.killTimer (self, int id)
The timer identifier is returned by startTimer() when a timer event isstarted.
See alsotimerEvent() and startTimer().
QMetaObject QObject.metaObject (self)
Returns a pointer to the meta-object of this object.
A meta-object contains information about a class that inheritsQObject, e.g. class name, superclassname, properties, signals and slots. Every QObject subclass that contains the Q_OBJECT macro will have ameta-object.
The meta-object information is required by the signal/slotconnection mechanism and the property system. The inherits() function also makes use ofthe meta-object.
If you have no pointer to an actual object instance but stillwant to access the meta-object of a class, you can use staticMetaObject.
Example:
See alsostaticMetaObject.
QObject.moveToThread (self, QThreadthread)
Changes the thread affinity for this object and its children.The object cannot be moved if it has a parent. Event processingwill continue in the targetThread.
To move an object to the main thread, use QApplication.instance() toretrieve a pointer to the current application, and then useQApplication.thread() toretrieve the thread in which the application lives. Forexample:
If targetThread is zero, all event processing for thisobject and its children stops.
Note that all active timers for the object will be reset. Thetimers are first stopped in the current thread and restarted (withthe same interval) in the targetThread. As a result,constantly moving an object between threads can postpone timerevents indefinitely.
A QEvent.ThreadChange eventis sent to this object just before the thread affinity is changed.You can handle this event to perform any special processing. Notethat any new events that are posted to this object will be handledin the targetThread.
Warning: This function is not thread-safe; thecurrent thread must be same as the current thread affinity. Inother words, this function can only 'push' an object from thecurrent thread to another thread, it cannot 'pull' an object fromany arbitrary thread to the current thread.
See alsothread().
QString QObject.objectName (self)
QObject QObject.parent (self)
Returns a pointer to the parent object.
See alsosetParent()and children().
QVariant QObject.property (self, str name)
Information about all available properties is provided throughthe metaObject() and dynamicPropertyNames().
See alsosetProperty(), QVariant.isValid(), metaObject(), and dynamicPropertyNames().
QObject.pyqtConfigure (self, object)
int QObject.receivers (self, SIGNAL() signal)
QObject.removeEventFilter (self, QObject)
Removes an event filter object obj from this object. Therequest is ignored if such an event filter has not beeninstalled.
All event filters for this object are automatically removed whenthis object is destroyed.
It is always safe to remove an event filter, even during eventfilter activation (i.e. Real money blackjack app usa today. from the eventFilter() function).
See alsoinstallEventFilter(),eventFilter(), and event().
QObject QObject.sender (self)
Returns a pointer to the object that sent the signal, if calledin a slot activated by a signal; otherwise it returns 0. Thepointer is valid only during the execution of the slot that callsthis function from this object's thread context.
The pointer returned by this function becomes invalid if thesender is destroyed, or if the slot is disconnected from thesender's signal.
Warning: This function violates the object-orientedprinciple of modularity. However, getting access to the sendermight be useful when many signals are connected to a singleslot.
Warning: As mentioned above, the return value of thisfunction is not valid when the slot is called via a Qt.DirectConnection from athread different from this object's thread. Do not use thisfunction in this type of scenario.
See alsosenderSignalIndex() andQSignalMapper.
int QObject.senderSignalIndex (self)
Returns the meta-method index of the signal that called thecurrently executing slot, which is a member of the class returnedby sender(). If called outside ofa slot activated by a signal, -1 is returned.
For signals with default parameters, this function will alwaysreturn the index with all parameters, regardless of which was usedwith connect(). For example, thesignal destroyed(QObject *obj = 0) will have two differentindexes (with and without the parameter), but this function willalways return the index with a parameter. This does not apply whenoverloading signals with different parameters.
Warning: This function violates the object-orientedprinciple of modularity. However, getting access to the signalindex might be useful when many signals are connected to a singleslot.
Warning: The return value of this function is not validwhen the slot is called via a Qt.DirectConnection from athread different from this object's thread. Do not use thisfunction in this type of scenario.
This function was introduced in Qt 4.8.
See alsosender(),QMetaObject.indexOfSignal(),and QMetaObject.method().
QObject.setObjectName (self, QString name)
QObject.setParent (self, QObject)
The QObject argument, if not None, causes self to be owned by Qt instead of PyQt.
Makes the object a child of parent.
See alsoparent() andQWidget.setParent().
bool QObject.setProperty (self, str name, QVariant value)
Information about all available properties is provided throughthe metaObject() and dynamicPropertyNames().
Dynamic properties can be queried again using property() and can be removed bysetting the property value to an invalid QVariant. Changing the value of a dynamicproperty causes a QDynamicPropertyChangeEventto be sent to the object.
Note: Dynamic properties starting with '_q_' are reservedfor internal purposes.
See alsoproperty(),metaObject(), and dynamicPropertyNames().
bool QObject.signalsBlocked (self)
See alsoblockSignals().
int QObject.startTimer (self, int interval)
A timer event will occur every interval millisecondsuntil killTimer() is called.If interval is 0, then the timer event occurs once everytime there are no more window system events to process.
The virtual timerEvent()function is called with the QTimerEvent event parameter class when atimer event occurs. Reimplement this function to get timerevents.
If multiple timers are running, the QTimerEvent.timerId() can be usedto find out which timer was activated.
Example:
Note that QTimer's accuracy depends onthe underlying operating system and hardware. Most platformssupport an accuracy of 20 milliseconds; some provide more. If Qt isunable to deliver the requested number of timer events, it willsilently discard some.
The QTimer class provides a high-levelprogramming interface with single-shot timers and timer signalsinstead of events. There is also a QBasicTimer class that is more lightweightthan QTimer and less clumsy than usingtimer IDs directly.
See alsotimerEvent(), killTimer(), and QTimer.singleShot().
QThread QObject.thread (self)
Returns the thread in which the object lives.
See alsomoveToThread().
QObject.timerEvent (self, QTimerEvent)
This event handler can be reimplemented in a subclass to receivetimer events for the object.
QTimer provides a higher-levelinterface to the timer functionality, and also more generalinformation about timers. The timer event is passed in theevent parameter.
See alsostartTimer(), killTimer(), and event().
QString QObject.tr (self, str sourceText, str disambiguation = None, int n = -1)
See Writing Source Codefor Translation for a detailed description of Qt's translationmechanisms in general, and the Disambiguationsection for information on disambiguation.
Warning: This method is reentrant only if all translatorsare installed before calling this method. Installing orremoving translators while performing translations is notsupported. Doing so will probably result in crashes or otherundesirable behavior.
See alsotrUtf8(),QApplication.translate(),QTextCodec.setCodecForTr(),and Internationalization withQt.
QString QObject.trUtf8 (self, str sourceText, str disambiguation = None, int n = -1)
See alsotr(), QApplication.translate(),and Internationalization withQt.
object QObject.__getattr__ (self, str name)
Qt Signal Documentation
void destroyed (QObject* = 0)
See alsodeleteLater() and QPointer.
Member Documentation
QMetaObject staticMetaObject
This member should be treated as a constant.
This variable stores the meta-object for the class.
A meta-object contains information about a class that inheritsQObject, e.g. class name, superclassname, properties, signals and slots. Every class that contains theQ_OBJECT macro will also have ameta-object.
The meta-object information is required by the signal/slotconnection mechanism and the property system. The inherits() function also makes use ofthe meta-object.
If you have a pointer to an object, you can use metaObject() to retrieve themeta-object associated with that object.
Example:
See alsometaObject().
PyQt 4.11.4 for X11 | Copyright © Riverbank Computing Ltd and The Qt Company 2015 | Qt 4.8.7 |
Get the full on-demand video here: http://www.ics.com/webinars/qt-beginners-part-5-ask-experts
In QML, I have a Text item with wrapMode: Text.Wrap but the text isn't wrapping. What am I doing wrong?
You need to set the width of the Text element, either directly using the width: property or by using anchors. Please refer to slide 3 of the presentation deck for some sample code that you can try.
Would it be possible to go into more detail with kit configuration for cross-platform development and remote deployment? Preferably with device configuration and deployment demonstration. To demonstrate the concept you could use any device, but I have a particular interest in a Raspberry Pi running Linux, and a Surface Pro running Windows 10.
That is a good suggestion but it could easily be the topic of an entire webinar in itself. We'll see if we can write a blog post that steps through how to configure Qt Creator for the Raspberry Pi, as that is a common and inexpensive platform. For a Surface Pro, I would imagine most people would develop natively on it (probably with a keyboard and mouse) so it would work like any desktop and Qt Creator should work mostly out of the box. I've used a Surface Pro this way.
I am having difficulty connecting to PostgreSQL from Qt. I looked at forums, followed their recommendations and still get 'Not Loaded'.There's a Russian and a Spanish step-by-step guide, is there something similar in English? I'm using Windows 7 x64 and MingW. I can connect directly using pgAdmin3, Valentina Studio, MS-Visual Studio, SQL Studio for PSQL, LibreOffice .
PostgreSQL is supported by Qt. I would start with one of the Qt database demos. Is the database on the same machine or remote? Hard to say what the issue could be without seeing the code and getting access to their database.
Should I use the QML Designer in Qt Creator? I heard it was not ready for production use.
Early versions of the QML Designer were pretty rough, but as of Qt Creator 4.0 it seems to be a lot more powerful and stable. We haven't had a lot of experience with it yet as Qt Creator 4.0 has only been out for a short time, but some of our developers are now starting to use it rather than hand writing all QML code as they did in the past.
I would like to develop a simple app to open up a URL to a website and then get information from the website that will populate some fields in my app. What is the easiest way to do this? Are there Qt Quick controls that can assist?
I would look at using the Qt Network module, to pull the relevant web pages from the server. Then parse the received HTML using string and/or regular expression classes to get the information you need. You might want to look at the Qt 'Network Download Example'. I don't think you would want to use QtWebKit or QtWebEngine. You could use Qt's XML support to parse the HTML, but only if you are sure that that the web pages are always valid XML/HTML, which might not be the case. There are some third party libraries you could use to parse HTML that might help if the web pages are very complex. Displaying the information is a different issue. You may want to use the Qt Quick Controls to develop your UX if you are using QML. It will also depend on whether this is a desktop or touchscreen application.
Is it possible to place a button widget over top of an QOpenGLWidget to make a UX comparable to Google maps? The button widget would be like the stationary user account button in Google maps while the map would live in the QOpenGLWidget. Ideally the button would be transparent. This person (https://stackoverflow.com/questions/16889319/put-transparent-qwidget-on…) did something similar by making the button a separate window that tracked the main window.
This is a little too advanced for this Qt For Beginners webinar. We could refer you to one of our developers and point you in the right direction to get started, or we'd be happy to develop some or all of the application as a paid consulting effort.
What are some of the pros and cons of using Qt resources?
Pros:
- Makes binary self-contained and avoids the need to ship as many files
- Avoids need to install files in platform-specific locations
- Can support different files for different platforms, screen sizes, languages, etc.
- Provides some protection against end users seeing your QML source files
- Easy to use and integrated into qmake and Qt Creator
Cons:
- Makes binaries larger
- Hard to update data, like translations, if they are in resources
- Data is not encrypted and can be extracted
Can you give me some guidance on whether to use qmake, qbs, or cmake as my build system?
Some of it comes down to personal preference and experience, but I would suggest in general: For small to medium sized projects, use qmake as it is simple and stable. For large projects, particularly those with non-Qt components, you should look at cmake. If you are interested in what may eventually be the replacement for qmake, take a look at qbs.
Can I use QML to create an editable TableView that uses SQLite as the backend datastore? If so, how do I do this? If not, is there another technique I can use to achieve an editable table with a database backend?
Without a connection made in C++ to the SQLite server? No, you will need to open a connection to act as an intermediary between the QML and the server. The connection provides the initial values and, when changes are made via QML, would send queries to commit changes made to the datastore.
WebEngine is not available for MinGW on Windows. Will WebEngine support for MinGW be available soon for 5.7 ?
Unfortunately the issue is that the Chromium engine that QtWebEngine uses as its web rendering engine does not support being built with the MinGW compiler. Fixing this would have to be done by the Chromium maintainers, and it seems that they are not interested in doing this. Chromium is huge, so it would be a significant effort. So this is not likely to happen any time soon. I can offer a couple of possible solutions. If the reason to use the MinGW compiler was due to cost, Visual Studio Express is available for free. If you want to go back to QtWebKit rather than QtWEbEngine, there is now a project to continue to maintain it. Some recent news can be found here: https://lists.webkit.org/pipermail/webkit-qt/2016-June/004063.html
How do you handle QMLTextEdit that anchored to bottom of screen on iOS and Android devices?
We would need a bit more information about what the issue is with TextEdit to help you. Are you having issues anchoring the element or is it giving you issues because it's anchored to the bottom of the screen?
I have heard that widgets are obsolete? Should I not be using them?
No, widgets are not obsolete. They are a mature module in Qt where few updates are expected in the forseeable future. They are applicable for desktop applications and can be used on embedded as well. With the computer industry seeing most growth in mobile, tablet, and embedded systems, QML tends to get the most attention.
How can I contribute to the Qt project?
Originally Qt was developed only by the 'Trolls,' employees of Trolltech. Just before Qt was acquired by Digia (now The Qt Company) it moved to an open governance process where anyone can contribute to Qt. If you want to do more than submit bugs, for example, you can submit source code patches into the Gerrit system, where they will be reviewed by other Qt developers, and either accepted or rejected for inclusion in a future release. Part of the review is running the changes in the CI system to ensure they compile and all existing automated unit tests pass. The basic process is to create an account on Gerrit, review and agree to the Qt Project's contribution agreement, clone Qt, submit your changes to Gerrit, and wait for review comments. If accepted, you submit the patch. It may take some back and forth discussion with the reviewers and several revisions before your patch is deemed to be acceptable. This wiki article covers the process in more detail: https://wiki.qt.io/Qt_Contribution_Guidelines
Are all Qt classes derived from QObject?
Surprisingly, not all of Qt's classes are derived QObject. QString, for instance, does not inherit from QObject nor does QVariant. QEvent is another. These non-QObject classes tend to be ones that are lighter weight and don't need to support signals and slots (like QString, for example).
Are there virtual slots? How about virtual signals?
Given that a slot boils down to a method, you can define one to be virtual, allowing derived classes to override its definition. Since the code for signals is generated by the moc tool, it doesn't really make sense to try to declare a signal as virtual.
Qt promises binary compatibility between releases. What does that mean?
A library is binary compatible if a program linked dynamically to a former version of the library continues running with newer versions of the library without the need to recompile. Qt maintains binary compatibility across major releases of Qt (e.g. Qt 5). Minor releases (e.g. Qt 5.5, Qt 5.6) are backwards binary compatible, that is a binary built with Qt 5.5 will run on Qt 5.6. They may not be forwards compatible, e.g. a Qt 5.6 binary may not run on Qt 5.5 because it may use features that were added in the newer version. With a patch release (e.g. Qt 5.6.0 and Qt 5.6.1), Qt aims to provide forward and backward binary compatibility. Major releases (e.g. Qt 5 and Qt 6) don't maintain binary compatibility but may be all or mostly source compatible. The implication on the Qt developers is that you need to follow certain rules when making changes (to Qt itself) to avoid breaking binary compatibility. That is why you may see people suggest certain changes and a comment that they can't happen before Qt 6.
What does the access level (public, private, protected) mean for slots?
Like any other function, it defines who has access to call an instance's slot. Public ones can obviously be called by code outside of the class, whereas protected and private slots are accessible only within a class. And even then private slots are only available to that class, not any derived classes. These rules apply only to method calls, Qt's connect() and related functions don't enforce the access levels at run-time when connecting to slots.
What is the recommended approach for fetching and displaying images on iOS using Apple's Photos framework and Qt Quick? Simply invoking the default image picker is not sufficient because the intention is to allow the user to select multiple images. On Android this is fairly straightforward: fetch a set of URLs in C++, and pass them in a model to a QML view whose delegate includes an Image. However, it does not appear to be possible to use URLs in this way on iOS unless the image is an asset in the project. Moreover, iOS image data (NSData *) cannot be fed directly into the constructor for QImage, for example, with the idea of wrapping the QImage in a sub-class of QQuickPaintedItem. So, what can we do?
This is a little too advanced for a Qt For Beginners webinar. We ran this by some of our developers and they had some ideas on how to approach it. QImage can take a char pointer and format as a source. These are probably both available from NSData if you can get the pixels. For example, NSData holds a CFData object which in turn holds CFDataGetBytePtr which is a pointer to byte array. The function CFDataGetBytePtr returns a pointer. That may be what you want but it would require more investigation.
What is the difference between Qt Quick and QML?
They are essentially the same. You can think of Qt Quick as the marketing name for the technology which includes the QML language and all of the related tools, components, etc. (like the QML compiler and components/controls).
What is a d-pointer?
Many Qt classes contain an instance variable called d_ptr. This is part of a design pattern called a d-pointer (also called opaque pointer) where the implementation details of a library may be hidden from its users and changes to the implementation can be made to a library without breaking binary compatibility. You can read about it in more detail in an article on the Qt wiki server: http://wiki.qt.io/Dpointer
I suspect I have a memory leak. How can I track it down?
Memory and resource leaks can be tough problems to solve. On Linux, the free valgrind tool is highly recommended for this. You can even run it from Qt Creator and it is supported on embedded Linux. When using the GNU C library, the GNU malloc and related functions have some support for extra checking using some environment variables and there are some functions you can call from the debugger to check memory allocation. On Windows we recommend Insure++ from Parasoft, but it is commercial and needs to be purchased.
Is there a way to make system() calls through Qt? For example, can I open the Windows notepad from within a Qt application?
You can use the standard C function system() to start another process. It is generally better though to use Qt's QProcess class to start other processes so it will not block your application and you can get information about the process through signals and slots. You could open the Windows notepad this way, although it is obviously not portable to other platforms. If want you want to do is open a text editor or viewer, you could use Qt's QDesktopServices class to do this in a portable way, as it will open whatever application is associated with a file type, such as a text file.
How can I know what Qt header files I need to include?
A good rule of thumb is to include the header file for every Qt class you use in your code. The Qt header files follow the convention of being named the same as the corresponding class. If you only need to declare a pointer to a class, you don't need to include it's header file, you can just declare it as a class, e.g 'class Foo;'.
Qt No Such Slot In Derived Class C
What is the preferred rendering back end to use for Qt on embedded Linux?
The most commonly used, especially for QML-based applications, is eglfs which uses OpenGL/ES. Widget-based applications sometimes use xcb (X11). Another option is linuxfb, which is the Linux frame buffer. The directfb driver is not recommended as the open source DirectFB project seems to be no longer maintained and the directfb.org web site is down.
Would using Qt and PostgreSQL with Visual Studio be easier to create a connection rather than MingW?
I understand that Visual Studio has some tools for building database interfaces, but the resulting code would not be portable to other platforms (which may or may not be an issue for you). Qt has database abstraction classes that I think would do much the same thing so you would not need to call the PostreSQL APIs directly, you could use classes from the Qt SQL module like QSqlDatabase that would make it easier.
You talked about using the Qt XML libraries for populating an application with website data, would this be the best option if it's a desktop application?
Qt No Such Slot In Derived Class Example
The Qt QML libraries are non-graphical so they would work with widget-based desktop applications. The issue may be that while HTML is technically XML, many web sites do not have well-formed HTML pages and parsing them as XML might result in errors. For simple web pages, string and regular expression functions might be enough to parse the web pages, or for more complex pages you could use a third party HTML parsing library.
What do you think about designing a complex application, for example, PhotoShop using QML. Is this really a good way to go ?
Qt No Such Slot In Derived Classes
Definitely doable. You may need to rethink the GUI if you aren't using Qt Quick Controls, as then you'll need to make your buttons and the like. I have definitely worked on projects as complex and Qt does provide you with all of the separate parts of something like Photoshop, so there's no reason why you could have it in one package.
Is it possible to create a 'runtime' app, that is similar to user created PDFs as a data input form?
Sure, you could make an app that acts like an editable pdf and then save it into a non-editable format.
In your reimplementation of this function, if you want to filterthe event out, i.e. stop it being handled further, returntrue; otherwise return false.
Example:
Notice in the example above that unhandled events are passed tothe base class's eventFilter() function, since the base class mighthave reimplemented eventFilter() for its own internal purposes.
Warning: If you delete the receiver object in thisfunction, be sure to return true. Otherwise, Qt will forward theevent to the deleted object and the program might crash.
See alsoinstallEventFilter().
QObject QObject.findChild (self, type type, QString name = QString())
If there is more than one child matching the search, the mostdirect ancestor is returned. If there are several direct ancestors,it is undefined which one will be returned. In that case, findChildren() should be used.
This example returns a child QPushButton of parentWidget named'button1':
This example returns a QListWidget child ofparentWidget:
See alsofindChildren().
QObject QObject.findChild (self, tuple types, QString name = QString())
list-of-QObject QObject.findChildren (self, type type, QString name = QString())
The following example shows how to find a list of child QWidgets of the specified parentWidgetnamed widgetname:
This example returns all QPushButtons that are childrenof parentWidget:
See alsofindChild().
list-of-QObject QObject.findChildren (self, tuple types, QString name = QString())
This function overloads findChildren().
Returns the children of this object that can be cast to type Tand that have names matching the regular expression regExp,or an empty list if there are no such objects. The search isperformed recursively.
list-of-QObject QObject.findChildren (self, type type, QRegExpregExp)
list-of-QObject QObject.findChildren (self, tuple types, QRegExpregExp)
bool QObject.inherits (self, str classname)
Returns true if this object is an instance of a class thatinherits className or a QObjectsubclass that inherits className; otherwise returnsfalse.
A class is considered to inherit itself.
Example:
If you need to determine whether an object is an instance of aparticular class for the purpose of casting it, consider usingqobject_cast(object) instead.
See alsometaObject() and qobject_cast().
QObject.installEventFilter (self, QObject)
Installs an event filter filterObj on this object. Forexample:
An event filter is an object that receives all events that aresent to this object. The filter can either stop the event orforward it to this object. The event filter filterObjreceives events via its eventFilter() function. The eventFilter() function must returntrue if the event should be filtered, (i.e. stopped); otherwise itmust return false.
If multiple event filters are installed on a single object, thefilter that was installed last is activated first.
Here's a KeyPressEater class that eats the key pressesof its monitored objects:
And here's how to install it on two widgets:
The QShortcut class, for example,uses this technique to intercept shortcut key presses.
Warning: If you delete the receiver object in youreventFilter() function, besure to return true. If you return false, Qt sends the event to thedeleted object and the program will crash.
Note that the filtering object must be in the same thread asthis object. If filterObj is in a different thread, thisfunction does nothing. If either filterObj or this objectare moved to a different thread after calling this function, theevent filter will not be called until both objects have the samethread affinity again (it is not removed).
See alsoremoveEventFilter(), eventFilter(), and event().
bool QObject.isWidgetType (self)
Calling this function is equivalent to callinginherits('QWidget'), except that it ismuch faster.
QObject.killTimer (self, int id)
The timer identifier is returned by startTimer() when a timer event isstarted.
See alsotimerEvent() and startTimer().
QMetaObject QObject.metaObject (self)
Returns a pointer to the meta-object of this object.
A meta-object contains information about a class that inheritsQObject, e.g. class name, superclassname, properties, signals and slots. Every QObject subclass that contains the Q_OBJECT macro will have ameta-object.
The meta-object information is required by the signal/slotconnection mechanism and the property system. The inherits() function also makes use ofthe meta-object.
If you have no pointer to an actual object instance but stillwant to access the meta-object of a class, you can use staticMetaObject.
Example:
See alsostaticMetaObject.
QObject.moveToThread (self, QThreadthread)
Changes the thread affinity for this object and its children.The object cannot be moved if it has a parent. Event processingwill continue in the targetThread.
To move an object to the main thread, use QApplication.instance() toretrieve a pointer to the current application, and then useQApplication.thread() toretrieve the thread in which the application lives. Forexample:
If targetThread is zero, all event processing for thisobject and its children stops.
Note that all active timers for the object will be reset. Thetimers are first stopped in the current thread and restarted (withthe same interval) in the targetThread. As a result,constantly moving an object between threads can postpone timerevents indefinitely.
A QEvent.ThreadChange eventis sent to this object just before the thread affinity is changed.You can handle this event to perform any special processing. Notethat any new events that are posted to this object will be handledin the targetThread.
Warning: This function is not thread-safe; thecurrent thread must be same as the current thread affinity. Inother words, this function can only 'push' an object from thecurrent thread to another thread, it cannot 'pull' an object fromany arbitrary thread to the current thread.
See alsothread().
QString QObject.objectName (self)
QObject QObject.parent (self)
Returns a pointer to the parent object.
See alsosetParent()and children().
QVariant QObject.property (self, str name)
Information about all available properties is provided throughthe metaObject() and dynamicPropertyNames().
See alsosetProperty(), QVariant.isValid(), metaObject(), and dynamicPropertyNames().
QObject.pyqtConfigure (self, object)
int QObject.receivers (self, SIGNAL() signal)
QObject.removeEventFilter (self, QObject)
Removes an event filter object obj from this object. Therequest is ignored if such an event filter has not beeninstalled.
All event filters for this object are automatically removed whenthis object is destroyed.
It is always safe to remove an event filter, even during eventfilter activation (i.e. Real money blackjack app usa today. from the eventFilter() function).
See alsoinstallEventFilter(),eventFilter(), and event().
QObject QObject.sender (self)
Returns a pointer to the object that sent the signal, if calledin a slot activated by a signal; otherwise it returns 0. Thepointer is valid only during the execution of the slot that callsthis function from this object's thread context.
The pointer returned by this function becomes invalid if thesender is destroyed, or if the slot is disconnected from thesender's signal.
Warning: This function violates the object-orientedprinciple of modularity. However, getting access to the sendermight be useful when many signals are connected to a singleslot.
Warning: As mentioned above, the return value of thisfunction is not valid when the slot is called via a Qt.DirectConnection from athread different from this object's thread. Do not use thisfunction in this type of scenario.
See alsosenderSignalIndex() andQSignalMapper.
int QObject.senderSignalIndex (self)
Returns the meta-method index of the signal that called thecurrently executing slot, which is a member of the class returnedby sender(). If called outside ofa slot activated by a signal, -1 is returned.
For signals with default parameters, this function will alwaysreturn the index with all parameters, regardless of which was usedwith connect(). For example, thesignal destroyed(QObject *obj = 0) will have two differentindexes (with and without the parameter), but this function willalways return the index with a parameter. This does not apply whenoverloading signals with different parameters.
Warning: This function violates the object-orientedprinciple of modularity. However, getting access to the signalindex might be useful when many signals are connected to a singleslot.
Warning: The return value of this function is not validwhen the slot is called via a Qt.DirectConnection from athread different from this object's thread. Do not use thisfunction in this type of scenario.
This function was introduced in Qt 4.8.
See alsosender(),QMetaObject.indexOfSignal(),and QMetaObject.method().
QObject.setObjectName (self, QString name)
QObject.setParent (self, QObject)
The QObject argument, if not None, causes self to be owned by Qt instead of PyQt.
Makes the object a child of parent.
See alsoparent() andQWidget.setParent().
bool QObject.setProperty (self, str name, QVariant value)
Information about all available properties is provided throughthe metaObject() and dynamicPropertyNames().
Dynamic properties can be queried again using property() and can be removed bysetting the property value to an invalid QVariant. Changing the value of a dynamicproperty causes a QDynamicPropertyChangeEventto be sent to the object.
Note: Dynamic properties starting with '_q_' are reservedfor internal purposes.
See alsoproperty(),metaObject(), and dynamicPropertyNames().
bool QObject.signalsBlocked (self)
See alsoblockSignals().
int QObject.startTimer (self, int interval)
A timer event will occur every interval millisecondsuntil killTimer() is called.If interval is 0, then the timer event occurs once everytime there are no more window system events to process.
The virtual timerEvent()function is called with the QTimerEvent event parameter class when atimer event occurs. Reimplement this function to get timerevents.
If multiple timers are running, the QTimerEvent.timerId() can be usedto find out which timer was activated.
Example:
Note that QTimer's accuracy depends onthe underlying operating system and hardware. Most platformssupport an accuracy of 20 milliseconds; some provide more. If Qt isunable to deliver the requested number of timer events, it willsilently discard some.
The QTimer class provides a high-levelprogramming interface with single-shot timers and timer signalsinstead of events. There is also a QBasicTimer class that is more lightweightthan QTimer and less clumsy than usingtimer IDs directly.
See alsotimerEvent(), killTimer(), and QTimer.singleShot().
QThread QObject.thread (self)
Returns the thread in which the object lives.
See alsomoveToThread().
QObject.timerEvent (self, QTimerEvent)
This event handler can be reimplemented in a subclass to receivetimer events for the object.
QTimer provides a higher-levelinterface to the timer functionality, and also more generalinformation about timers. The timer event is passed in theevent parameter.
See alsostartTimer(), killTimer(), and event().
QString QObject.tr (self, str sourceText, str disambiguation = None, int n = -1)
See Writing Source Codefor Translation for a detailed description of Qt's translationmechanisms in general, and the Disambiguationsection for information on disambiguation.
Warning: This method is reentrant only if all translatorsare installed before calling this method. Installing orremoving translators while performing translations is notsupported. Doing so will probably result in crashes or otherundesirable behavior.
See alsotrUtf8(),QApplication.translate(),QTextCodec.setCodecForTr(),and Internationalization withQt.
QString QObject.trUtf8 (self, str sourceText, str disambiguation = None, int n = -1)
See alsotr(), QApplication.translate(),and Internationalization withQt.
object QObject.__getattr__ (self, str name)
Qt Signal Documentation
void destroyed (QObject* = 0)
See alsodeleteLater() and QPointer.
Member Documentation
QMetaObject staticMetaObject
This member should be treated as a constant.
This variable stores the meta-object for the class.
A meta-object contains information about a class that inheritsQObject, e.g. class name, superclassname, properties, signals and slots. Every class that contains theQ_OBJECT macro will also have ameta-object.
The meta-object information is required by the signal/slotconnection mechanism and the property system. The inherits() function also makes use ofthe meta-object.
If you have a pointer to an object, you can use metaObject() to retrieve themeta-object associated with that object.
Example:
See alsometaObject().
PyQt 4.11.4 for X11 | Copyright © Riverbank Computing Ltd and The Qt Company 2015 | Qt 4.8.7 |
Get the full on-demand video here: http://www.ics.com/webinars/qt-beginners-part-5-ask-experts
In QML, I have a Text item with wrapMode: Text.Wrap but the text isn't wrapping. What am I doing wrong?
You need to set the width of the Text element, either directly using the width: property or by using anchors. Please refer to slide 3 of the presentation deck for some sample code that you can try.
Would it be possible to go into more detail with kit configuration for cross-platform development and remote deployment? Preferably with device configuration and deployment demonstration. To demonstrate the concept you could use any device, but I have a particular interest in a Raspberry Pi running Linux, and a Surface Pro running Windows 10.
That is a good suggestion but it could easily be the topic of an entire webinar in itself. We'll see if we can write a blog post that steps through how to configure Qt Creator for the Raspberry Pi, as that is a common and inexpensive platform. For a Surface Pro, I would imagine most people would develop natively on it (probably with a keyboard and mouse) so it would work like any desktop and Qt Creator should work mostly out of the box. I've used a Surface Pro this way.
I am having difficulty connecting to PostgreSQL from Qt. I looked at forums, followed their recommendations and still get 'Not Loaded'.There's a Russian and a Spanish step-by-step guide, is there something similar in English? I'm using Windows 7 x64 and MingW. I can connect directly using pgAdmin3, Valentina Studio, MS-Visual Studio, SQL Studio for PSQL, LibreOffice .
PostgreSQL is supported by Qt. I would start with one of the Qt database demos. Is the database on the same machine or remote? Hard to say what the issue could be without seeing the code and getting access to their database.
Should I use the QML Designer in Qt Creator? I heard it was not ready for production use.
Early versions of the QML Designer were pretty rough, but as of Qt Creator 4.0 it seems to be a lot more powerful and stable. We haven't had a lot of experience with it yet as Qt Creator 4.0 has only been out for a short time, but some of our developers are now starting to use it rather than hand writing all QML code as they did in the past.
I would like to develop a simple app to open up a URL to a website and then get information from the website that will populate some fields in my app. What is the easiest way to do this? Are there Qt Quick controls that can assist?
I would look at using the Qt Network module, to pull the relevant web pages from the server. Then parse the received HTML using string and/or regular expression classes to get the information you need. You might want to look at the Qt 'Network Download Example'. I don't think you would want to use QtWebKit or QtWebEngine. You could use Qt's XML support to parse the HTML, but only if you are sure that that the web pages are always valid XML/HTML, which might not be the case. There are some third party libraries you could use to parse HTML that might help if the web pages are very complex. Displaying the information is a different issue. You may want to use the Qt Quick Controls to develop your UX if you are using QML. It will also depend on whether this is a desktop or touchscreen application.
Is it possible to place a button widget over top of an QOpenGLWidget to make a UX comparable to Google maps? The button widget would be like the stationary user account button in Google maps while the map would live in the QOpenGLWidget. Ideally the button would be transparent. This person (https://stackoverflow.com/questions/16889319/put-transparent-qwidget-on…) did something similar by making the button a separate window that tracked the main window.
This is a little too advanced for this Qt For Beginners webinar. We could refer you to one of our developers and point you in the right direction to get started, or we'd be happy to develop some or all of the application as a paid consulting effort.
What are some of the pros and cons of using Qt resources?
Pros:
- Makes binary self-contained and avoids the need to ship as many files
- Avoids need to install files in platform-specific locations
- Can support different files for different platforms, screen sizes, languages, etc.
- Provides some protection against end users seeing your QML source files
- Easy to use and integrated into qmake and Qt Creator
Cons:
- Makes binaries larger
- Hard to update data, like translations, if they are in resources
- Data is not encrypted and can be extracted
Can you give me some guidance on whether to use qmake, qbs, or cmake as my build system?
Some of it comes down to personal preference and experience, but I would suggest in general: For small to medium sized projects, use qmake as it is simple and stable. For large projects, particularly those with non-Qt components, you should look at cmake. If you are interested in what may eventually be the replacement for qmake, take a look at qbs.
Can I use QML to create an editable TableView that uses SQLite as the backend datastore? If so, how do I do this? If not, is there another technique I can use to achieve an editable table with a database backend?
Without a connection made in C++ to the SQLite server? No, you will need to open a connection to act as an intermediary between the QML and the server. The connection provides the initial values and, when changes are made via QML, would send queries to commit changes made to the datastore.
WebEngine is not available for MinGW on Windows. Will WebEngine support for MinGW be available soon for 5.7 ?
Unfortunately the issue is that the Chromium engine that QtWebEngine uses as its web rendering engine does not support being built with the MinGW compiler. Fixing this would have to be done by the Chromium maintainers, and it seems that they are not interested in doing this. Chromium is huge, so it would be a significant effort. So this is not likely to happen any time soon. I can offer a couple of possible solutions. If the reason to use the MinGW compiler was due to cost, Visual Studio Express is available for free. If you want to go back to QtWebKit rather than QtWEbEngine, there is now a project to continue to maintain it. Some recent news can be found here: https://lists.webkit.org/pipermail/webkit-qt/2016-June/004063.html
How do you handle QMLTextEdit that anchored to bottom of screen on iOS and Android devices?
We would need a bit more information about what the issue is with TextEdit to help you. Are you having issues anchoring the element or is it giving you issues because it's anchored to the bottom of the screen?
I have heard that widgets are obsolete? Should I not be using them?
No, widgets are not obsolete. They are a mature module in Qt where few updates are expected in the forseeable future. They are applicable for desktop applications and can be used on embedded as well. With the computer industry seeing most growth in mobile, tablet, and embedded systems, QML tends to get the most attention.
How can I contribute to the Qt project?
Originally Qt was developed only by the 'Trolls,' employees of Trolltech. Just before Qt was acquired by Digia (now The Qt Company) it moved to an open governance process where anyone can contribute to Qt. If you want to do more than submit bugs, for example, you can submit source code patches into the Gerrit system, where they will be reviewed by other Qt developers, and either accepted or rejected for inclusion in a future release. Part of the review is running the changes in the CI system to ensure they compile and all existing automated unit tests pass. The basic process is to create an account on Gerrit, review and agree to the Qt Project's contribution agreement, clone Qt, submit your changes to Gerrit, and wait for review comments. If accepted, you submit the patch. It may take some back and forth discussion with the reviewers and several revisions before your patch is deemed to be acceptable. This wiki article covers the process in more detail: https://wiki.qt.io/Qt_Contribution_Guidelines
Are all Qt classes derived from QObject?
Surprisingly, not all of Qt's classes are derived QObject. QString, for instance, does not inherit from QObject nor does QVariant. QEvent is another. These non-QObject classes tend to be ones that are lighter weight and don't need to support signals and slots (like QString, for example).
Are there virtual slots? How about virtual signals?
Given that a slot boils down to a method, you can define one to be virtual, allowing derived classes to override its definition. Since the code for signals is generated by the moc tool, it doesn't really make sense to try to declare a signal as virtual.
Qt promises binary compatibility between releases. What does that mean?
A library is binary compatible if a program linked dynamically to a former version of the library continues running with newer versions of the library without the need to recompile. Qt maintains binary compatibility across major releases of Qt (e.g. Qt 5). Minor releases (e.g. Qt 5.5, Qt 5.6) are backwards binary compatible, that is a binary built with Qt 5.5 will run on Qt 5.6. They may not be forwards compatible, e.g. a Qt 5.6 binary may not run on Qt 5.5 because it may use features that were added in the newer version. With a patch release (e.g. Qt 5.6.0 and Qt 5.6.1), Qt aims to provide forward and backward binary compatibility. Major releases (e.g. Qt 5 and Qt 6) don't maintain binary compatibility but may be all or mostly source compatible. The implication on the Qt developers is that you need to follow certain rules when making changes (to Qt itself) to avoid breaking binary compatibility. That is why you may see people suggest certain changes and a comment that they can't happen before Qt 6.
What does the access level (public, private, protected) mean for slots?
Like any other function, it defines who has access to call an instance's slot. Public ones can obviously be called by code outside of the class, whereas protected and private slots are accessible only within a class. And even then private slots are only available to that class, not any derived classes. These rules apply only to method calls, Qt's connect() and related functions don't enforce the access levels at run-time when connecting to slots.
What is the recommended approach for fetching and displaying images on iOS using Apple's Photos framework and Qt Quick? Simply invoking the default image picker is not sufficient because the intention is to allow the user to select multiple images. On Android this is fairly straightforward: fetch a set of URLs in C++, and pass them in a model to a QML view whose delegate includes an Image. However, it does not appear to be possible to use URLs in this way on iOS unless the image is an asset in the project. Moreover, iOS image data (NSData *) cannot be fed directly into the constructor for QImage, for example, with the idea of wrapping the QImage in a sub-class of QQuickPaintedItem. So, what can we do?
This is a little too advanced for a Qt For Beginners webinar. We ran this by some of our developers and they had some ideas on how to approach it. QImage can take a char pointer and format as a source. These are probably both available from NSData if you can get the pixels. For example, NSData holds a CFData object which in turn holds CFDataGetBytePtr which is a pointer to byte array. The function CFDataGetBytePtr returns a pointer. That may be what you want but it would require more investigation.
What is the difference between Qt Quick and QML?
They are essentially the same. You can think of Qt Quick as the marketing name for the technology which includes the QML language and all of the related tools, components, etc. (like the QML compiler and components/controls).
What is a d-pointer?
Many Qt classes contain an instance variable called d_ptr. This is part of a design pattern called a d-pointer (also called opaque pointer) where the implementation details of a library may be hidden from its users and changes to the implementation can be made to a library without breaking binary compatibility. You can read about it in more detail in an article on the Qt wiki server: http://wiki.qt.io/Dpointer
I suspect I have a memory leak. How can I track it down?
Memory and resource leaks can be tough problems to solve. On Linux, the free valgrind tool is highly recommended for this. You can even run it from Qt Creator and it is supported on embedded Linux. When using the GNU C library, the GNU malloc and related functions have some support for extra checking using some environment variables and there are some functions you can call from the debugger to check memory allocation. On Windows we recommend Insure++ from Parasoft, but it is commercial and needs to be purchased.
Is there a way to make system() calls through Qt? For example, can I open the Windows notepad from within a Qt application?
You can use the standard C function system() to start another process. It is generally better though to use Qt's QProcess class to start other processes so it will not block your application and you can get information about the process through signals and slots. You could open the Windows notepad this way, although it is obviously not portable to other platforms. If want you want to do is open a text editor or viewer, you could use Qt's QDesktopServices class to do this in a portable way, as it will open whatever application is associated with a file type, such as a text file.
How can I know what Qt header files I need to include?
A good rule of thumb is to include the header file for every Qt class you use in your code. The Qt header files follow the convention of being named the same as the corresponding class. If you only need to declare a pointer to a class, you don't need to include it's header file, you can just declare it as a class, e.g 'class Foo;'.
Qt No Such Slot In Derived Class C
What is the preferred rendering back end to use for Qt on embedded Linux?
The most commonly used, especially for QML-based applications, is eglfs which uses OpenGL/ES. Widget-based applications sometimes use xcb (X11). Another option is linuxfb, which is the Linux frame buffer. The directfb driver is not recommended as the open source DirectFB project seems to be no longer maintained and the directfb.org web site is down.
Would using Qt and PostgreSQL with Visual Studio be easier to create a connection rather than MingW?
I understand that Visual Studio has some tools for building database interfaces, but the resulting code would not be portable to other platforms (which may or may not be an issue for you). Qt has database abstraction classes that I think would do much the same thing so you would not need to call the PostreSQL APIs directly, you could use classes from the Qt SQL module like QSqlDatabase that would make it easier.
You talked about using the Qt XML libraries for populating an application with website data, would this be the best option if it's a desktop application?
Qt No Such Slot In Derived Class Example
The Qt QML libraries are non-graphical so they would work with widget-based desktop applications. The issue may be that while HTML is technically XML, many web sites do not have well-formed HTML pages and parsing them as XML might result in errors. For simple web pages, string and regular expression functions might be enough to parse the web pages, or for more complex pages you could use a third party HTML parsing library.
What do you think about designing a complex application, for example, PhotoShop using QML. Is this really a good way to go ?
Qt No Such Slot In Derived Classes
Definitely doable. You may need to rethink the GUI if you aren't using Qt Quick Controls, as then you'll need to make your buttons and the like. I have definitely worked on projects as complex and Qt does provide you with all of the separate parts of something like Photoshop, so there's no reason why you could have it in one package.
Is it possible to create a 'runtime' app, that is similar to user created PDFs as a data input form?
Sure, you could make an app that acts like an editable pdf and then save it into a non-editable format.
Is it possible to get a cross-reference of function usage when compiling a desktop application?
There is nothing built in to Qt or Qt Creator but there are lots of third party tools for creating cross-references. One example is LXR, see http://lxr.sourceforge.net/en/index.php You could integrate this into your build process. If want you really want to do is locate certain symbols in source code, Qt Creator can do this for you.