I am trying to give focus to a window if the user clicks on another window.
Right now i have two windows: Window A is behind, and Window B is in front. When Window B
self.raise_()
followed by a self.activateWindow()
should be the commands you are looking for, although there seems to be some kind of issues with that on my Debian OS, for example, if I click on a window that is maximized, the window will obtain focus, but it will also disappear, looks like some kind of bug, the sequence in the setTopLevelWindow
method will circumvent that behaviour:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)
from PyQt4 import QtGui, QtCore, QtWebKit, QtNetwork
class myWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(myWindow, self).__init__(parent)
self.button = QtGui.QPushButton(self)
self.button.setText("Show Dialog")
self.dialog = QtGui.QDialog(self)
self.dialog.setFocusPolicy(QtCore.Qt.StrongFocus)
self.dialog.installEventFilter(self)
self.button.clicked.connect(self.dialog.show)
self.setCentralWidget(self.button)
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.WindowDeactivate:
self.setTopLevelWindow()
self.dialog.close()
return True
return False
def setTopLevelWindow(self):
if self.windowState() != QtCore.Qt.WindowMaximized:
self.showMaximized()
self.showNormal()
else:
self.showNormal()
self.showMaximized()
self.raise_()
self.activateWindow()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
app.setApplicationName('myWindow')
main = myWindow()
main.show()
sys.exit(app.exec_())