To display a wxPython window in full screen mode you use:
ShowFullScreen(True)
How do you get out of full screen though? I've tried the obvious way:
ShowFullScreen(True)
sleep(5)
ShowFullScreen(False)
This doesn't work though. When I run the script, nothing appears. After 5 seconds a window roughly 200x250 appears in the top-left corner of the screen, without anything inside of it. It doesn't appear to have any borders either.
If I change this to
showFullScreen(True)
then I get stuck with a full screen window that I have to use Alt + F2 -> xkill to get out of.
It looks like you need to Show() the window first. (According to the documentation, you shouldn't have to. Maybe this is a bug.) I tested on Mac OS X and Windows - they both exhibit issues if you don't call Show() first.
Also note that you shouldn't sleep in the main GUI thread. You'll hang the UI. Using CallLater is one potential solution, as shown in my example.
Working example:
import wx
def main():
app = wx.PySimpleApp()
frame = wx.Frame(None, -1, 'Full Screen Test')
frame.Show()
frame.ShowFullScreen(True)
wx.CallLater(5000, frame.ShowFullScreen, False)
app.MainLoop()
if __name__ == '__main__':
main()
The documentation for ShowFullScreen reads:
ShowFullScreen(show, style=wx.FULLSCREEN_ALL)
Depending on the value of show parameter the window is either shown full screen or restored to its normal state.
Parameters:
show (bool)
style (long): is a bit list containing some or all of the following values, which indicate what elements of the window to hide in full-screen mode:
wx.FULLSCREEN_NOMENUBAR
wx.FULLSCREEN_NOTOOLBAR
wx.FULLSCREEN_NOSTATUSBAR
wx.FULLSCREEN_NOBORDER
wx.FULLSCREEN_NOCAPTION
wx.FULLSCREEN_ALL (all of the above)
So put your Full Screen toggle event/s in a Menu and start full screen mode with:
self.window.ShowFullScreen(True, style=(wx.FULLSCREEN_NOTOOLBAR | wx.FULLSCREEN_NOSTATUSBAR |wx.FULLSCREEN_NOBORDER |wx.FULLSCREEN_NOCAPTION))
Note that I omitted wx.FULLSCREEN_NOMENUBAR, in this way you will still be able to access the menu to turn full screen mode off again.
Related
this works perfectly if window is not minimized, but when window is minimized i am not be able to set the focus on it.
from pywinauto.application import Application
app = Application(backend="uia")
try:
app = app.connect(title_re=".*Bloc*.", visible_only=False)
except:
print("Not visible...")
exit()
app_top_window = app.top_window()
app_top_window.maximize()
How to workaround this and bring the minimized window to the foreground again?
If connect calls works fine, it should work like this:
top_window = app.window(title_re=".*Bloc*.", visible_only=False)
top_window.restore().set_focus() # sometimes .restore() is redundant
app.top_window() is not recommended to use as it sticks to the top window at the moment of .top_window() call. Top window may change at any moment. Also it's for visible top window only.
I'm trying to take a screenshot of the current active window in PyQt5. I know the generic method to take an screenshot of any window is QScreen::grabWindow(winID), for which winID is an implementation-specific ID depending on the window system. Since I'm running X and KDE, I plan to eventual use CTypes to call Xlib, but for now, I simply execute "xdotool getactivewindow" to obtain the windowID in a shell.
For a minimum exmaple, I created a QMainWindow with a QTimer. When the timer is fired, I identify the active window ID by executing "xdotool getactivewindow", get its return value, call grabWindow() to capture the active window, and display the screetshot in a QLabel. On startup, I also set my window a fixed 500x500 size for observation, and activate Qt.WindowStaysOnTopHint flag, so that my window is still visible when it's not in focus. To put them together, the implementation is the following code.
from PyQt5 import QtCore, QtGui, QtWidgets
import subprocess
class ScreenCapture(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)
self.setFixedHeight(500)
self.setFixedWidth(500)
self.label = QtWidgets.QLabel(self)
self.timer = QtCore.QTimer(self)
self.timer.setInterval(500)
self.timer.timeout.connect(self.timer_handler)
self.timer.start()
self.screen = QtWidgets.QApplication.primaryScreen()
#QtCore.pyqtSlot()
def timer_handler(self):
window = int(subprocess.check_output(["xdotool", "getactivewindow"]).decode("ascii"))
self.screenshot = self.screen.grabWindow(window)
self.label.setPixmap(self.screenshot)
self.label.setFixedSize(self.screenshot.size())
if __name__ == '__main__':
app = QtWidgets.QApplication([])
window = ScreenCapture()
window.show()
app.exec()
To test the implementation, I started the script and clicked another window. It appears to work without problems if there is no overlap between my application window and the active window. See the following screenshot, when Firefox (right) is selected, my application is able to capture the active window of Firefox and display it in the QLabel.
However, the screenshot doesn't work as expected if there is an overlap between the application window and the active window. The window of the application itself will be captured, and creates a positive feedback.
If there is an overlap between the application window and the active window. The window of the application itself will be captured, and creates a positive feedback.
I've already disabled the 3D composite in KDE's settings, but the problem remains. The examples above are taken with all composite effects disabled.
Question
Why isn't this implementation working correctly when the application window and the active window are overlapped? I suspect it's an issue caused by some forms of unwanted interaction between graphics systems (Qt toolkit, window manager, X, etc), but I'm not sure.
Is it even possible solve this problem? (Note: I know I can hide() before the screenshot and show() it again, but it doesn't really solve this problem, which is taking a screenshot even if an overlap exists.)
As pointed out by #eyllanesc, it appears that it is not possible to do it in Qt, at least not with QScreen::grabWindow, because grabWindow() doesn't actually grab the window itself, but merely the area occupied by the window. The documentation contains the following warning.
The grabWindow() function grabs pixels from the screen, not from the window, i.e. if there is another window partially or entirely over the one you grab, you get pixels from the overlying window, too. The mouse cursor is generally not grabbed.
The conclusion is that it's impossible do to it in pure Qt. It's only possible to implement such a functionality by writing a low-level X program. Since the question asks for a solution "in Qt", any answer that potentially involves deeper, low-level X solutions are out-of-scope. This question can be marked as resolved.
The lesson to learn here: Always check the documentation before using a function or method.
Update: I managed to solve the problem by reading the window directly from X via Xlib. Somewhat ironically, my solution uses GTK to grab the window and sends its result to Qt... Anyway, you can write the same program with Xlib directly if you don't want to use GTK, but I used GTK since the Xlib-related functions in GDK is pretty convenient to demonstrate the basic concept.
To get a screenshot, we first convert our window ID to an GdkWindow suitable for use within GDK, and we call Gdk.pixbuf_get_from_window() to grab the window and store it in a gdk_pixbuf. Finally, we call save_to_bufferv() to convert the raw pixbuf to a suitable image format and store it in a buffer. At this point, the image in the buffer is suitable to use in any program, including Qt.
The documentation contains the following warning:
If the window is off the screen, then there is no image data in the obscured/offscreen regions to be placed in the pixbuf. The contents of portions of the pixbuf corresponding to the offscreen region are undefined.
If the window you’re obtaining data from is partially obscured by other windows, then the contents of the pixbuf areas corresponding to the obscured regions are undefined.
If the window is not mapped (typically because it’s iconified/minimized or not on the current workspace), then NULL will be returned.
If memory can’t be allocated for the return value, NULL will be returned instead.
It also has some remarks about compositing,
gdk_display_supports_composite has been deprecated since version 3.16 and should not be used in newly-written code.
Compositing is an outdated technology that only ever worked on X11.
So basically, it's only possible to grab a partially obscured window under X11 (not possible in Wayland!), with a compositing window manager. I tested it without compositing, and found the window is blacked-out when compositing is disabled. But when composition is enabled, it seems to work without problem. It may or may not work for your application. But I think if you are using compositing under X11, it probably will work.
from PyQt5 import QtCore, QtGui, QtWidgets
import subprocess
class ScreenCapture(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setWindowFlags(self.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)
self.setFixedHeight(500)
self.setFixedWidth(500)
self.label = QtWidgets.QLabel(self)
self.screen = QtWidgets.QApplication.primaryScreen()
self.timer = QtCore.QTimer(self)
self.timer.setInterval(500)
self.timer.timeout.connect(self.timer_handler)
self.timer.start()
#staticmethod
def grab_screenshot():
from gi.repository import Gdk, GdkX11
window_id = int(subprocess.check_output(["xdotool", "getactivewindow"]).decode("ascii"))
display = GdkX11.X11Display.get_default()
window = GdkX11.X11Window.foreign_new_for_display(display, window_id)
x, y, width, height = window.get_geometry()
pb = Gdk.pixbuf_get_from_window(window, 0, 0, width, height)
if pb:
buf = pb.save_to_bufferv("bmp", (), ())
return buf[1]
else:
return
#QtCore.pyqtSlot()
def timer_handler(self):
screenshot = self.grab_screenshot()
self.pixmap = QtGui.QPixmap()
if not self.pixmap:
return
self.pixmap.loadFromData(screenshot)
self.label.setPixmap(self.pixmap)
self.label.setFixedSize(self.pixmap.size())
if __name__ == '__main__':
app = QtWidgets.QApplication([])
window = ScreenCapture()
window.show()
app.exec()
Now it captures an active window perfectly, even if there are overlapping windows on top of it.
I'm trying to use QSplashScreen as a 'simple' notification window. I build the actual notification in a dialog and am then trying to use QPixmap.grabWidget() on that and pass the pixmap to the SplashScreen but its not showing. So I'm wondering if the problem is due to me trying to use it post-start.
Simplified version of what I'm doing.
class NotifyHandler:
def showNotify(self, event):
widget = NotifyWidget.createInstance(event) # Build the QDialog
#Do I need to do widget.show()?
pixmap = QtGui.QPixmap.grabWidget(widget) # Convert to pixmap
splash = QtGui.QSplashScreen(pixmap, QtCore.Qt.WindowStayOnTopHint)
(x,y) = getDisplayLocation(splash) # Get coords to put it in bottom-right corner
splash.setGeometry(splash.width(), splash.height(), x, y)
splash.show()
QtCore.QTimer.singleShot(3000, splash.close)
I try this however nothing shows up. If I try it as a Dialog though:
widget.show()
widget.raise_()
widget.activateWindow()
It works fine. So I figure either I can't do this post-launch or there is something going on when I try to feed it a pixmap of a widget. Any ideas?
It seems my dialog issue and splash screen were having the same sort of issue.
I forgot that if you don't assign the dialog (or Splash screen in this case) to a scope outside the method then the GC will just eat the object after the method returns.
So by simply adding something like:
self.splash = splash
self.splash.show()
QtCore.QTimer.singleShot(3000, self.splash.close)
The splash screen wouldn't be garbage collected and I get my splash screen.
I would like to make a window in PyQt that you can click through; ie click on a window and the click is passed through so you can interact with whatever is behind it, while the window remains on top. An example of the effect I am trying to achieve is like the notifications on Ubuntu which appear in the top-right hand corner by default, which you can click through.
I would like to be able to do this in PyQt ideally; if not, my platform is linux but windows solutions are also welcome!
Cheers for the help in advance! I've been giving this a bit of thought and research, it would be great to be able to do this.
EDIT: I am trying to make a window you can use like tracing paper for the window behind
Here is a solution on Windows using PyQt4.
You need to override the eventFilter in the Front widget (on Windows it is winEvent) and then forward the events to the Back window.
I'm not completely sure, but there must be a similar approach that can be used on other platforms (instead of winEvent, maybe x11Event?)
Good luck!
from PyQt4 import QtCore, QtGui
import win32api, win32con, win32gui, win32ui
class Front(QtGui.QPushButton):
def __init__(self,text="",whndl=None):
super(Front,self).__init__(text)
self.pycwnd = win32ui.CreateWindowFromHandle(whndl)
# install an event filter for Windows' messages. Forward messages to
# the other HWND
def winEvent(self,MSG):
# forward Left button down message to the other window. Not sure
# what you want to do exactly, so I'm only showing a left button click. You could
if MSG.message == win32con.WM_LBUTTONDOWN or \
MSG.message == win32con.WM_LBUTTONUP:
print "left click in front window"
self.pycwnd.SendMessage(MSG.message, MSG.wParam, MSG.lParam)
return True, 0 # tells Qt to ignore the message
return super(Front,self).winEvent(MSG)
class Back(QtGui.QPushButton):
def __init__(self,text=""):
super(Back,self).__init__(text)
self.clicked.connect(self.onClick)
def onClick(self):
print 'back has been clicked'
def main():
a = QtGui.QApplication([])
back = Back("I'm in back...")
back.setWindowTitle("I'm in back...")
back.show()
# Get the HWND of the window in back (You need to use the exact title of that window)
whndl = win32gui.FindWindowEx(0, 0, None, "I'm in back...")
# I'm just making the front button bigger so that it is obvious it is in front ...
front = Front(text="*____________________________*",whndl=whndl)
front.setWindowOpacity(0.8)
front.show()
a.exec_()
if __name__ == "__main__":
main()
self.setAttribute(Qt.WA_TransparentForMouseEvents, True)
self.setAttribute(Qt.WA_NoChildEventsForParent, True)
self.setWindowFlags(Qt.Window|Qt.X11BypassWindowManagerHint|Qt.WindowStaysOnTopHint|Qt.FramelessWindowHint)
self.setAttribute(Qt.WA_TranslucentBackground)
This works. It is tested on Linux Mint 20.1 Cinnamon.
That means the parent blocked it WA_TransparentForMouseEvents all the time
I am having a problem with wxPython. I am attempting to have a scrollable window without a visible scroll bar. I still want to be able to use the mouse wheel to scroll as well as use the keyboard shortcuts that I have written.
I have the following simplified code:
import wx
import wx.stc
app = wx.App(0)
frame = wx.Frame(None, wx.ID_ANY, "Sample Scroll pane")
textViewer = wx.stc.StyledTextCtrl(frame, wx.ID_ANY)
textViewer.Text = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22"
textViewer.SetUseVerticalScrollBar(False)
textViewer.ScrollLines(1)
frame.Show()
app.MainLoop()
I am using the "ScrollLines" function to scroll my text programatically. On a windows machine this works as expected and scrolls down one line. However, on Ubuntu, the text does not scroll if the "SetUseVerticalScrollBar" is false.
How can I hide my scrollbar while maintaining it's functionality in a cross platform manner?
ScrollToLine seems to work consistently on Windows and Linux, so you could replace the ScrollLines call with something like this:
first = textViewer.GetFirstVisibleLine()
textViewer.ScrollToLine(first + n)
where n is the number of lines to scroll down.