[C++] Confused by KWindowInfo behavior

Hello! In my Qt/QML application I’m trying to get the list of all windows, check if a window with a given class name is present and print the WId, and if not present run it inside a QProcess and then return the WId. Here’s my code:

int Embedder::launch(const QString &program)
{
	m_process->setProgram(program);
	m_process->startDetached(); // also tried start()
	return m_process->processId();
}

int Embedder::kwinGetId(const QString &Class){
	QList<WId> windows = KX11Extras::windows();

	for (WId window : windows) {
		auto windoInfo = KWindowInfo(window, NET::WMVisibleName, NET::WM2WindowClass);
		qWarning() << window << windoInfo.visibleName() << windoInfo.windowClassName();
		if(windoInfo.windowClassName() == Class){
			return window;
		}
	}
	return -1;
}

int Embedder::waitForId(const QString &Class){
	int ID;
	QElapsedTimer timer;
    timer.start();
	while(timer.elapsed() < 5000){ // after tot ms exit
		ID = kwinGetId(Class);
		if(ID > 0){
			return ID;
		} else {
			sleep(0.05);
		}
	}
	return -1;
}

m_wid = getId(Class);
	if(m_wid < 1){
		// launch
		launch(program);
		m_wid = waitForId(Class);
		if(m_wid < 1){
			return false;
		}
	}

what I get is a list of all windows plus the desktop and plasmashell, the app specified (kate) is correctly run, but it’s not displayed in the list. It’s like it doesn’t see the app he just run. If the app is already running it works instead. what can be the problem?

thanks in advance!

1 Like

I think your problem might be the way you wait for the new window. Busy waiting in a loop like this might prevent the relevant events from getting processed.

Instead I’d suggest you connect to the KX11Extras::windowAdded signal to get notified about new windows and test whether the new window is the one you expected

1 Like

This works very very VERY well! thank you! What do you think was the problem of my waiting loop?