2

I need a QWindow to capture screenChanged signal in object A.
I have QWidget B that has Qt::Window flag.
B is a parent of A.
After object of class A was created I am trying to call connect like this:

bool isOk = connect(b->window()->windowHandle(), SIGNAL(screenChanged(...)), a, SLOT(...)));
assert(isOk);

I am getting an error that tells:
QObject::connect: Cannot connect (null)::screenChanged(QScreen*) to CFloatingEdit::onScreenChanged()

Why b->window()->windowHandle() is zero?
Am I trying to make with screenChanged the right way?

Vladimir Tsyshnatiy
  • 989
  • 1
  • 10
  • 20

2 Answers2

2

Merged comments to the answer:

Steeve: Take a look at the implementation of windowForWidget function in Ming-Ming Cheng's answer in this question.

arturx64: The nullptr will be returned if your widget is NOT native. Are you sure that you use appropriate widget? By the way, you can set the Qt::WA_NativeWindow attribute on widgets to make it native.

Vladimir Tsyshnatiy
  • 989
  • 1
  • 10
  • 20
0

The working code should look like below. Clarification is into the comments.

// Connect a slot to handle the screen change eve
auto wid = this->winId(); // important!!! it forces "windowHandle()" to get valid "QWindow*" 

QWindow* window = this->windowHandle();
connectionsuccess = connect(window, SIGNAL(screenChanged(QScreen *)), this, SLOT(myScreenChanged(QScreen *)));
Q_ASSERT(connectionsuccess);

...

// capture when app window moved to other display
void MainWindow::myScreenChanged(QScreen* screen)
{
    qDebug() << screen->name() << screen->geometry()<< screen->name();
}
Buzz
  • 1,102
  • 1
  • 9
  • 24