framelesswindowhint 导致 qmenu 无法正常工作
Posted
技术标签:
【中文标题】framelesswindowhint 导致 qmenu 无法正常工作【英文标题】:framelesswindowhint causes qmenu to not working correctly 【发布时间】:2019-02-17 15:39:46 【问题描述】:我是 pyqt 的新手。我想摆脱 qmenu 阴影。但是当我添加 framelesswindowhint 时,菜单无法正常工作。
实现无框窗口之前的代码:
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
class MainWindow(QtWidgets.QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.setMinimumSize(800, 400)
self.setStyleSheet(
"""
background-color:white;
"""
)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.mainlayout = QtWidgets.QVBoxLayout()
button = QtWidgets.QPushButton("my button")
filemenu = QtWidgets.QMenu(button)
#filemenu.setWindowFlags(QtCore.Qt.FramelessWindowHint)
filemenu.setObjectName("filemenu")
openaction = QtWidgets.QAction("open item", self)
filemenu.addAction(openaction)
button.setMenu(filemenu)
self.mainlayout.addWidget(button)
self.setLayout(self.mainlayout)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
# app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
mw = MainWindow()
# mw.setWindowOpacity(0.95)
mw.show()
sys.exit(app.exec_())
输出:(单击按钮):
取消注释后: (未点击按钮)
(点击按钮)
【问题讨论】:
【参考方案1】:Qt.NoDropShadowWindowHint
禁用支持平台上的窗口投影。
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
class MainWindow(QtWidgets.QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.label = QtWidgets.QLabel(self, alignment=QtCore.Qt.AlignCenter)
button = QtWidgets.QPushButton("my button")
filemenu = QtWidgets.QMenu(button)
filemenu.triggered.connect(self.selected)
#filemenu.setWindowFlags(QtCore.Qt.FramelessWindowHint) # ---
filemenu.setWindowFlags(filemenu.windowFlags() # +++
| QtCore.Qt.NoDropShadowWindowHint) # +++
openaction = QtWidgets.QAction("open item", self)
filemenu.addAction(openaction)
filemenu.addAction("Do something...")
button.setMenu(filemenu)
self.mainlayout = QtWidgets.QVBoxLayout()
self.mainlayout.addStretch()
self.mainlayout.addWidget(self.label)
self.mainlayout.addWidget(button)
self.mainlayout.addStretch()
self.setLayout(self.mainlayout)
def selected(self, q):
self.label.setText(q.text() + ' selected')
CSS = """
QWidget
background-color: white;
QMenu
background-color: #ABABAB; /* sets background of the menu */
border: 1px solid black;
margin: 0;
QMenu::item
background-color: red;
QMenu::item:selected
background-color: #654321;
QMenu::separator
height: 12px;
background: lightblue;
margin-left: 10px;
margin-right: 5px;
QLabel
color: red;
font: 27px;
QPushButton
background-color: yellow;
"""
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
# app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
app.setStyleSheet(CSS)
mw = MainWindow()
# mw.setWindowOpacity(0.95)
mw.setMinimumSize(800, 400)
mw.show()
sys.exit(app.exec_())
【讨论】:
以上是关于framelesswindowhint 导致 qmenu 无法正常工作的主要内容,如果未能解决你的问题,请参考以下文章
添加属性 QtCore.Qt.FramelessWindowHint 后如何从边缘调整窗口大小
QT FramelessWindowHint Windows 7 停靠在一边