Finally I am able to create a chrome like tab in Qt/PyQt QMainWindow. After unsuccessfully trying to port this Qt C++ non client area painting code, I revise my thinking to be this way : trick visually by displaying a free floating QFrame that get resized and moved together with main window. Surely this is not a perfect solution (for example this code still don't solve when to disable topmost hint where the another application is on top of the main application window, but I think that's quite easy to solve)
What I want to ask in this page, is how to keep the click action on this QFrame window button from stealing focus from main window? At the moment I simply reactivate the main window when click action does occur. But it creates flashing effect on the mainwindow titlebar. I believe this SO page gives the answer, but I haven't been able to create a successful result from this C++ code:
HWND winHandle = (HWND)winId();
ShowWindow(winHandle, SW_HIDE);
SetWindowLong(winHandle, GWL_EXSTYLE, GetWindowLong(winHandle, GWL_EXSTYLE)
| WS_EX_NOACTIVATE | WS_EX_APPWINDOW);
ShowWindow(winHandle, SW_SHOW);
Into this PyQt code:
def no_focus(self):
import ctypes, win32con, win32gui
dc = win32gui.GetWindowDC(self.winId())
user32 = ctypes.windll.user32
user32.SetWindowLongW(dc, win32con.GWL_EXSTYLE, user32.GetWindowLongW(dc, win32con.GWL_EXSTYLE) | win32con.WS_EX_NOACTIVATE | win32con.WS_EX_APPWINDOW)
Would love to let you see and test the fully functional code below:
__author__ = 'Eko Wibowo'
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class FSTabHeader(QFrame):
def __init__(self, parent):
super(FSTabHeader, self).__init__(None)
self.mainwindow = parent
self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.SplashScreen)
self.setFocusPolicy(Qt.NoFocus)
self.setAttribute(Qt.WA_ShowWithoutActivating)
layout = QHBoxLayout(self)
layout.setSpacing(0)
layout.setContentsMargins(0, 0, 0, 0)
tab_text = 'Click me'
self.btn_tab = QPushButton(self)
self.btn_tab.setStyleSheet('border:1px')
self.btn_tab.setContentsMargins(0,0,0,0)
self.btn_tab.setText(tab_text)
self.btn_tab.setMinimumHeight(25 + 1)
self.btn_tab.setMaximumHeight(25 + 1)
self.btn_tab.setMinimumWidth(60)
self.btn_tab.setMaximumWidth(60)
self.btn_tab.setCursor(Qt.PointingHandCursor)
self.btn_tab.clicked.connect(self.dummy)
layout.addWidget(self.btn_tab)
self.setLayout(layout)
self.show()
def dummy(self):
print 'it create flashes effect on mainwindow titlebar'
self.mainwindow.activateWindow()
def no_focus(self):
import ctypes, win32con, win32gui
dc = win32gui.GetWindowDC(self.winId())
user32 = ctypes.windll.user32
user32.SetWindowLongW(dc, win32con.GWL_EXSTYLE, user32.GetWindowLongW(dc, win32con.GWL_EXSTYLE) | win32con.WS_EX_NOACTIVATE | win32con.WS_EX_APPWINDOW)
def adjust_position(self):
top_left = self.mainwindow.mapToGlobal(self.mainwindow.rect().topLeft())
self.move(top_left.x() + 20 + 5, top_left.y() - self.height() + 1)
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.tab_header = FSTabHeader(self)
self.tab_header.no_focus()
def resizeEvent(self, *args, **kwargs):
self.tab_header.adjust_position()
def moveEvent(self, *args, **kwargs):
self.tab_header.adjust_position()
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
mainWindow = MainWindow(None)
mainWindow.show()
app.exec_()
Any suggestions?
Related
I'm trying to create a video player similar to the looks of the default GUI for mpv. I'm using a QGraphicsVideoItem inside a QGraphicsView along with a custom ControlBar widget as the OSC.
I want the OSC to be 100px high and video.width()px wide, and always flush with the bottom edge of the QGraphicsView widget. I can't seem to do either of those requirements.
MRE:
from PySide6 import QtWidgets as qtw
from PySide6 import QtGui as qtg
from PySide6 import QtCore as qtc
from PySide6 import QtMultimedia as qtm
from PySide6 import QtMultimediaWidgets as qtmw
class ControlBar(qtw.QWidget):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.setStyleSheet("background: red")
class View(qtw.QGraphicsView):
def __init__(self) -> None:
super().__init__()
self.setMouseTracking(True)
self.setRenderHints(qtg.QPainter.RenderHint.SmoothPixmapTransform | qtg.QPainter.RenderHint.Antialiasing)
self.setViewportMargins(-2, -2, -2, -2) # `QGraphicsView` has hard coded margins.
self.setFrameStyle(qtw.QFrame.Shape.NoFrame)
self._scene = qtw.QGraphicsScene()
self._video_item = qtmw.QGraphicsVideoItem()
self._control_bar = ControlBar()
self._media_player = qtm.QMediaPlayer()
self._scene.addItem(self._video_item)
self._proxy_control_bar = self._scene.addWidget(self._control_bar)
self._proxy_control_bar.setFlag(qtw.QGraphicsItem.GraphicsItemFlag.ItemIgnoresTransformations)
self.setScene(self._scene)
self._media_player.setVideoOutput(self._video_item)
self._media_player.setSource("video")
self._media_player.mediaStatusChanged.connect(self._media_player.play)
def showEvent(self, event) -> None:
qtc.QTimer.singleShot(100, lambda: self.fitInView(self._video_item, qtc.Qt.AspectRatioMode.KeepAspectRatio))
def resizeEvent(self, event) -> None:
self._proxy_control_bar.setGeometry(0, 0, self.viewport().width(), 100)
pos = qtc.QPoint(0, self.height() - self._proxy_control_bar.size().height())
self._proxy_control_bar.setPos(0, self.mapToScene(pos).y())
self.fitInView(self._video_item, qtc.Qt.AspectRatioMode.KeepAspectRatio)
app = qtw.QApplication()
view = View()
view.show()
app.exec()
I've been able to set the height of the widget to 100px, but using control_area.setGeometry(..., ..., self.viewport().width(), ...) sets the width to be a bit more than the video's width. And, for some reason, adding self._control_bar to the scene creates all this extra empty space around the two items, I have no idea why.
My questions are,
is there no way to get the actual size (specifically the width) of the video item after a fitInView call?
Because calling item.size() even after a fitInView call just returns the original size of the item, which I guess makes sense since only the view's view of the item was "fit in view" and the item itself is still the same.
How do I set the position of the control_bar to be where I want it to?
As seen in one of the videos below, the way I'm doing it right now does not accomplish it at all.
What's up with all the extra empty space?
How it looks:
Video with self._proxy_control_bar lines left in.
Video with self._proxy_control_bar lines commented out.
Could be a either a Qt bug, or a bug in my app, I am hoping someone can help me diagnose this.
I am building a PyQt5 application with an interface built using qtdesigner and pyuic5.
I have to QSpinBox widgets in my window, which I connect to two methods like this:
self.img1IndexBox.valueChanged.connect(self.changeImage1)
self.img2IndexBox.valueChanged.connect(self.changeImage2)
Everything seems to work fine in the application, except for one thing: If I scroll the mouse over the spinbox, I can make it increment the value. If I change the value with text, all works fine. If I use keyboard arrows on the spinbox, it works fine. But if I click on either the up or down arrows from the spinbox, I get get two changeValue events, a double increment. Like I clicked twice. In fact, it even looks from the animation that it is creating an event for the downpress, and another when the button goes back up.
Could this be just a library bug, or what could be causing this in my program? How could I debug this?
You might be able to prevent that double thing by setting spinbox enable to false.
then make it enable to true after processing large data.
Upon clicking the arrow up/down
on_valuechanged
ui->spinbox->setEnabled(false);
then set to true before the function on_valuechanged ends.
ui->spinbox->setEnabled(true);
Apparently the problem is the event is triggering a very long routine, this delays the "button release" event, and it is enough time to make the system think the user is actually holding the button, generating more events... But I would still be interested in learning what would be a good walk-around. Would there be a nice pyqt-onic way to start a thread for that method?
http://www.qtcentre.org/archive/index.php/t-43078.html
Instead of using valueChanged.connect use editingFinished.connect it will make sure the function is called only after value is provided.
PyQt
import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDoubleSpinBox, QApplication, QMainWindow, QWidget, QVBoxLayout, QLabel, QSpinBox
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.initUI()
# def valueChanged(self, value):
# print(value)
def valueChanged(self):
print(f"Value changed new value is : {self.spinBox.value()}")
def initUI(self):
self.setGeometry(0, 0, 200, 100)
self.layout = QVBoxLayout()
self.spinBox = QSpinBox()
self.spinBox.setAlignment(Qt.AlignCenter)
self.spinBox.setRange(0, 1000)
# self.spinBox.valueChanged.connect(self.valueChanged)
self.spinBox.editingFinished.connect(self.valueChanged)
self.layout.addWidget(self.spinBox)
self.setLayout(self.layout)
if __name__ == "__main__":
app = QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec())
PySide
import sys
from PySide6.QtWidgets import QDoubleSpinBox, QApplication, QMainWindow, QWidget, QVBoxLayout, QLabel, QSpinBox
from PySide6.QtGui import Qt
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.initUI()
# def valueChanged(self, value):
# print(value)
def valueChanged(self):
print(f"Value changed new value is : {self.spinBox.value()}")
def initUI(self):
self.setGeometry(0, 0, 200, 100)
self.layout = QVBoxLayout()
self.spinBox = QSpinBox()
self.spinBox.setAlignment(Qt.AlignCenter)
self.spinBox.setRange(0, 1000)
# self.spinBox.valueChanged.connect(self.valueChanged)
self.spinBox.editingFinished.connect(self.valueChanged)
self.layout.addWidget(self.spinBox)
self.setLayout(self.layout)
if __name__ == "__main__":
app = QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec())
I want my application to terminate all drag and drops in a dragLeaveEvent, without the user releasing the mouse button.
The problem is that the loop suspends all events that could cancel a QDrag while it is happening, even though the documentation states:
"On Linux and Mac OS X, the drag and drop operation can take some
time, but this function does not block the event loop. Other events
are still delivered to the application while the operation is
performed. On Windows, the Qt event loop is blocked during the
operation. However, QDrag.exec() on Windows causes processEvents() to
be called frequently to keep the GUI responsive. If any loops or
operations are called while a drag operation is active, it will block
the drag operation."
Because of this, I cannot call events which would end the drag.
So far, I've tried what is suggested here, as seen in the code. I'm using PyQt5, but if a solution works in Qt it should work in PyQt.
Edit: I'm a little scared to delete the drag, as the scene does not own it. I suppose I could set it up to own it though, but as was posted here it should not work.
Edit2: Added code with my non-working attempts to fix it. I'd really like to solve this issue without having to make my own drag-drop framework. Also trimmed post.
import sys
from PyQt5.QtWidgets import (QMainWindow, QApplication,
QGraphicsView, QGraphicsScene, QGraphicsWidget, QGraphicsRectItem)
from PyQt5.QtCore import (QMimeData, Qt, QByteArray, QCoreApplication,
QEvent, QPoint)
from PyQt5.QtGui import QBrush, QColor, QDrag, QPen, QMouseEvent
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.scene = CustomScene()
self.view = QGraphicsView(self.scene, self)
self.setGeometry(100, 100, 600, 600)
self.view.setGeometry(0, 0, 500, 500)
self.show()
class CustomScene(QGraphicsScene):
def __init__(self):
super().__init__()
self.customWidgets = []
for i in range(5):
newItem = CustomDragWidget()
self.addItem(newItem)
self.customWidgets.append(newItem)
newItem.setGeometry(i * 50, i * 50, 50, 50)
def dragLeaveEvent(self, event):
# Work your magic here. I've tried the following:
# 1)
self.customWidgets[0].dropEvent(event)
# 2)
self.dropEvent(event)
# 3)
eve = QMouseEvent(QEvent.MouseButtonRelease, QPoint(0, 0), Qt.LeftButton, Qt.LeftButton, Qt.NoModifier)
QCoreApplication.sendEvent(self.views()[0], eve)
QCoreApplication.processEvents()
# 4)
eve = QMouseEvent(QEvent.MouseButtonRelease, QPoint(0, 0), Qt.LeftButton, Qt.LeftButton, Qt.NoModifier)
QCoreApplication.sendEvent(self.customWidgets[0], eve)
QCoreApplication.processEvents()
def dropEvent(self, QGraphicsSceneDragDropEvent):
# a dummy dropevent that tries to stop the drop, but doesnt work
QGraphicsSceneDragDropEvent.accept()
class CustomDragWidget(QGraphicsWidget):
def __init__(self,):
super().__init__()
self.squareItem = QGraphicsRectItem()
self.squareItem.setBrush(QBrush(QColor(Qt.blue)))
self.squareItem.setPen(QPen(QColor(Qt.black), 2))
self.squareItem.setRect(0, 0, 50, 50)
self.squareItem.setParentItem(self)
self.setAcceptDrops(True)
def mousePressEvent(self, event):
mime = QMimeData()
itemData = QByteArray()
mime.setData('application/x-dnditemdata', itemData)
drag = QDrag(self)
drag.setMimeData(mime)
drag.exec(Qt.MoveAction)
def dropEvent(self, event):
event.accept()
if __name__ == '__main__':
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
This is a little bit hackish, but it seems to work (on Linux, anyway):
def dragLeaveEvent(self, event):
QCoreApplication.postEvent(self,
QKeyEvent(QEvent.KeyPress, Qt.Key_Escape, Qt.NoModifier))
I tried using the Qt documentation example to restrict the rectangle to the area of the scene but it still fails, someone has an alternative to do this?
My code, the QGraphicsView instance was created in Qt Desginer:
# -*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
from screen import *
class MovableItem(QGraphicsRectItem):
def __init__(self, rectang, *args, **kwargs):
QGraphicsRectItem.__init__(self, rectang, *args, **kwargs)
self.setFlags(QGraphicsItem.ItemIsMovable |
QGraphicsItem.ItemSendsGeometryChanges)
self.pen = QPen(Qt.darkMagenta)
self.pen.setWidth(4)
self.setPen(self.pen)
def itemChange(self, change, value):
if change == QGraphicsItem.ItemPositionChange and self.scene():
# value is the new position.
self.newPos = value.toPointF()
self.rect = self.scene().sceneRect()
if not(self.rect.contains(self.newPos)):
# Keep the item inside the scene rect.
self.newPos.setX(min(self.rect.right(), max(self.newPos.x(), self.rect.left())))
self.newPos.setY(min(self.rect.bottom(), max(self.newPos.y(), self.rect.top())))
return self.newPos
return QGraphicsRectItem.itemChange(self, change, value)
class Main(QWidget, Ui_Form):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
self.setupUi(self)
self.scene = QGraphicsScene()
self.cena.setScene(self.scene)
self.scene.addPixmap(QPixmap("01.png"))
self. graph = MovableItem(2, 2, 300, 150)
self.scene.addItem(self.graph)
def showEvent(self, event):
self.cena.fitInView(self.scene.sceneRect(), Qt.IgnoreAspectRatio)
app = QApplication(sys.argv)
window = Main()
window.show()
sys.exit(app.exec_())
First:
Use setSceneRect() in your main Main(), to set the size of the scene.
Second:
Actually the example of the documentation is wrong, therefore, to adjust the rectangle to the scene, delete this if and subtract, in min, the parameters right and bottom by the rectangle dimensions right and bottom in setX and setY. Replace this part of your code:
if not(self.rect.contains(self.newPos)):
# Keep the item inside the scene rect.
self.newPos.setX(min(self.rect.right(), max(self.newPos.x(), self.rect.left())))
self.newPos.setY(min(self.rect.bottom(), max(self.newPos.y(), self.rect.top())))
return self.newPos
For:
self.newPos.setX(min(self.rect.right()-self.boundingRect().right(), max(self.newPos.x(), self.rect.left())))
self.newPos.setY(min(self.rect.bottom()-self.boundingRect().bottom(), max(self.newPos.y(), self.rect.top())))
return self.newPos
If the active window belongs to some other process,how to make the QMessageBox or QmainWindow of this example in front of any overlapping sibling widgets when timeout ?
I tried raise_() and activateWindow() ,but both don’t work on WinXP
import sys
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class MainWindow(QWidget):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.resize(800,600)
self.lcdNumber = QLCDNumber()
self.lcdNumber.setNumDigits(8)
layout = QVBoxLayout(self)
layout.addWidget(self.lcdNumber)
self.currentTime = QTime(0,0,0)
self.lcdNumber.display(self.currentTime.toString('hh:mm:ss'))
self.timer = QTimer(self)
self.timer.timeout.connect(self.updateLcdNumberContent)
self.timer.start(1000)
def updateLcdNumberContent(self):
self.currentTime = self.currentTime.addSecs(1)
self.lcdNumber.display(self.currentTime.toString('hh:mm:ss'))
if self.currentTime == QTime(0,0,4) :
msgBox = QMessageBox(self)
msgBox.setWindowTitle('iTimer')
msgBox.setIcon (QMessageBox.Information)
msgBox.setText("Time Out !!")
stopButton = msgBox.addButton("Stop", QMessageBox.ActionRole)
ignoreButton = msgBox.addButton(QMessageBox.Ignore)
stopButton.clicked.connect(self.timer.stop)
msgBox.show()
# self.raise_()
# self.activateWindow()
if __name__ == '__main__':
app =QApplication(sys.argv)
frame = MainWindow()
frame.show()
sys.exit(app.exec_())
Try to modify window flags by using QWidget::setWindowFlags() method of your QMessageBox or QMainWindow. You should use Qt::WindowStaysOnTopHint flag for your purpose.
It will be something like window->setWindowFlags(window->windowFlags() | Qt::WindowStaysOnTopHint).
If you will not succeed with just setWindowFlags(window->windowFlags() | Qt::WindowStaysOnTopHint), you will need to use Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint with another flags. Experiment with it and you'll succeed.