Add QObject.delete() and QObject.deleteLater(), and test QObject deletion

This commit is contained in:
Simon Edwards 2022-05-01 20:02:02 +02:00
parent cbb3f99dfa
commit 02f901ddf1
4 changed files with 37 additions and 4 deletions

View File

@ -99,7 +99,18 @@
} else { \
return env.Null(); \
} \
}
} \
Napi::Value deleteLater(const Napi::CallbackInfo& info) { \
Napi::Env env = info.Env(); \
this->instance->deleteLater(); \
return env.Null(); \
} \
Napi::Value deleteObject(const Napi::CallbackInfo& info) { \
Napi::Env env = info.Env(); \
delete static_cast<QObject*>(this->instance); \
return env.Null(); \
} \
// Ideally this macro below should go in
// QOBJECT_WRAPPED_METHODS_DECLARATION_WITH_EVENT_SOURCE but some wrappers
@ -143,7 +154,9 @@
InstanceMethod("setParent", &ComponentWrapName::setParent), \
InstanceMethod("startTimer", &ComponentWrapName::startTimer), \
InstanceMethod("killTimer", &ComponentWrapName::killTimer), \
InstanceMethod("parent", &ComponentWrapName::parent),
InstanceMethod("parent", &ComponentWrapName::parent), \
InstanceMethod("deleteLater", &ComponentWrapName::deleteLater), \
InstanceMethod("delete", &ComponentWrapName::deleteObject),
#endif // QOBJECT_WRAPPED_METHODS_EXPORT_DEFINE

View File

@ -147,8 +147,8 @@ class DLL_EXPORT WrapperCache : public QObject {
static Napi::FunctionReference destroyedCallback;
public Q_SLOTS:
void handleDestroyed(const QObject* object) {
uint64_t ptrHash = extrautils::hashPointerTo53bit(object);
void handleDestroyed(const QObject* qobject) {
uint64_t ptrHash = extrautils::hashPointerTo53bit(qobject);
if (!this->cache.contains(ptrHash)) {
return;
}

View File

@ -64,6 +64,12 @@ export class QObject<Signals extends QObjectSignals = QObjectSignals> extends Ev
killTimer(timerId: number): void {
this.native.killTimer(timerId);
}
delete(): void {
this.native.delete();
}
deleteLater(): void {
this.native.deleteLater();
}
}
export interface QObjectSignals {

View File

@ -59,5 +59,19 @@ describe('WrapperCache using CacheTestQObject', () => {
expect((<any>b.parent())['magic']).toBe(true);
});
it('QObject.delete() clears the native field', () => {
const a = new QObject();
a.delete();
expect(a.native).toBeNull();
});
it('QObject.delete() clears chains of QObjects and their native field', () => {
const a = new QObject();
const b = new QObject(a);
a.delete();
expect(a.native).toBeNull();
expect(b.native).toBeNull();
});
qApp.quit();
});