Skip to content

Commit 8347ee3

Browse files
committed
增加右键菜单
1 parent fb2d7c3 commit 8347ee3

File tree

11 files changed

+232
-90
lines changed

11 files changed

+232
-90
lines changed

.settings/org.eclipse.core.resources.prefs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
eclipse.preferences.version=1
22
encoding//Resources/Data/Projects/PyQt/Demo/FacePoints.py=utf-8
3+
encoding//Resources/Data/Projects/PyQt/QMenu/MultiSelect.py=utf-8
34
encoding//Resources/Data/Projects/PyQt/QWebView/GetCookie.py=utf-8
45
encoding//Test/BaseApplyStyle.py=utf-8
56
encoding//Test/CustomCursor.py=utf-8

Resources/Themes/Dark/style.qss

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -529,3 +529,18 @@ QScrollBar::add-line:vertical {
529529
background: transparent;
530530
subcontrol-position:bottom;
531531
}
532+
533+
/*菜单*/
534+
QMenu {
535+
color: black;
536+
border: 0px solid rgb(255, 255, 255);
537+
background: rgb(255, 255, 255);
538+
}
539+
QMenu::item {
540+
padding: 8px 30px;
541+
border-bottom: 1px solid rgba(200, 200, 200, 255);
542+
}
543+
QMenu::item:selected {
544+
color: white;
545+
background: rgba(38, 38, 38, 200);
546+
}

Resources/Themes/Default/style.qss

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -529,3 +529,18 @@ QScrollBar::add-line:vertical {
529529
background: transparent;
530530
subcontrol-position:bottom;
531531
}
532+
533+
/*菜单*/
534+
QMenu {
535+
color: black;
536+
border: 0px solid rgb(255, 255, 255);
537+
background: rgb(255, 255, 255);
538+
}
539+
QMenu::item {
540+
padding: 8px 30px;
541+
border-bottom: 1px solid rgba(200, 200, 200, 255);
542+
}
543+
QMenu::item:selected {
544+
color: white;
545+
background: rgba(39, 174, 97, 200);
546+
}

Test/TestToolTip.py

Lines changed: 67 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,67 @@
1-
#!/usr/bin/env python
2-
# -*- coding: utf-8 -*-
3-
4-
"""
5-
Created on 2019年1月2日
6-
@author: Irony
7-
@site: https://pyqt5.com https://github.com/892768447
8-
@email: 892768447@qq.com
9-
@file: Test.TestToolTip
10-
@description:
11-
"""
12-
from PyQt5.QtWidgets import QWidget
13-
14-
from Widgets.ToolTip import ToolTip
15-
16-
17-
__Author__ = """By: Irony
18-
QQ: 892768447
19-
Email: 892768447@qq.com"""
20-
__Copyright__ = 'Copyright (c) 2019 Irony'
21-
__Version__ = 1.0
22-
23-
24-
class TestWindow(QWidget):
25-
26-
def __init__(self, *args, **kwargs):
27-
super(TestWindow, self).__init__(*args, **kwargs)
28-
layout = QHBoxLayout(self)
29-
btn1 = QPushButton('鼠标悬停1', self, minimumHeight=38, toolTip='这是按钮1')
30-
ToolTip.bind(btn1)
31-
layout.addWidget(btn1)
32-
33-
btn2 = QPushButton('鼠标悬停2', toolTip='这是按钮2')
34-
ToolTip.bind(btn2)
35-
layout.addWidget(btn2)
36-
37-
38-
if __name__ == '__main__':
39-
import sys
40-
from PyQt5.QtWidgets import QApplication, QHBoxLayout, QPushButton
41-
app = QApplication(sys.argv)
42-
app.setStyleSheet("""ToolTip > QLabel {
43-
color: white;
44-
border-radius: 5px;
45-
padding: 10px;
46-
background-color: rgba(77, 77, 77, 180);
47-
}""")
48-
w = TestWindow()
49-
w.show()
50-
sys.exit(app.exec_())
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
"""
5+
Created on 2019年1月2日
6+
@author: Irony
7+
@site: https://pyqt5.com https://github.com/892768447
8+
@email: 892768447@qq.com
9+
@file: Test.TestToolTip
10+
@description:
11+
"""
12+
from PyQt5.QtWidgets import QWidget
13+
14+
from Widgets.ToolTip import ToolTip
15+
from PyQt5.QtCore import QTimer
16+
17+
18+
__Author__ = """By: Irony
19+
QQ: 892768447
20+
Email: 892768447@qq.com"""
21+
__Copyright__ = 'Copyright (c) 2019 Irony'
22+
__Version__ = 1.0
23+
24+
25+
class TestWindow(QWidget):
26+
27+
def __init__(self, *args, **kwargs):
28+
super(TestWindow, self).__init__(*args, **kwargs)
29+
self.resize(600, 400)
30+
layout = QHBoxLayout(self)
31+
btn1 = QPushButton('鼠标悬停1', self, minimumHeight=38, toolTip='这是按钮1')
32+
ToolTip.bind(btn1)
33+
layout.addWidget(btn1)
34+
35+
btn2 = QPushButton('鼠标悬停2', toolTip='这是按钮2')
36+
ToolTip.bind(btn2)
37+
layout.addWidget(btn2)
38+
39+
def showEvent(self, event):
40+
super(TestWindow, self).showEvent(event)
41+
if not hasattr(self, '_tip'):
42+
def test():
43+
self._tip = ToolTip()
44+
self._tip.setText('底部居中提示')
45+
self._tip.show()
46+
self._tip.move(
47+
self.pos().x() + int((self.width() - self._tip.width()) / 2),
48+
self.pos().y() + self.height() - 20,
49+
)
50+
self._tip._hideTimer.timeout.connect(self._tip.close)
51+
self._tip._hideTimer.start(2000)
52+
QTimer.singleShot(1000, test)
53+
54+
55+
if __name__ == '__main__':
56+
import sys
57+
from PyQt5.QtWidgets import QApplication, QHBoxLayout, QPushButton
58+
app = QApplication(sys.argv)
59+
app.setStyleSheet("""ToolTip > QLabel {
60+
color: white;
61+
border-radius: 5px;
62+
padding: 10px;
63+
background-color: rgba(77, 77, 77, 180);
64+
}""")
65+
w = TestWindow()
66+
w.show()
67+
sys.exit(app.exec_())

UiFiles/MainWindow.ui

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -385,11 +385,11 @@
385385
<number>4</number>
386386
</property>
387387
<item>
388-
<widget class="QWebView" name="webViewContent">
388+
<widget class="QWebView" name="webViewContent" native="true">
389389
<property name="contextMenuPolicy">
390-
<enum>Qt::NoContextMenu</enum>
390+
<enum>Qt::CustomContextMenu</enum>
391391
</property>
392-
<property name="url">
392+
<property name="url" stdset="0">
393393
<url>
394394
<string>about:blank</string>
395395
</url>

UiFiles/Ui_MainWindow.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ def setupUi(self, FormMainWindow):
146146
self.verticalLayout_3.setSpacing(0)
147147
self.verticalLayout_3.setObjectName("verticalLayout_3")
148148
self.webViewContent = QtWebKitWidgets.QWebView(self.widgetContents)
149-
self.webViewContent.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
149+
self.webViewContent.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
150150
self.webViewContent.setUrl(QtCore.QUrl("about:blank"))
151151
self.webViewContent.setObjectName("webViewContent")
152152
self.verticalLayout_3.addWidget(self.webViewContent)

Utils/CommonUtil.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,12 @@
99
@file: Utils.CommonUtil
1010
@description: 公共工具类
1111
"""
12+
import ctypes
1213
import hashlib
1314
import logging
1415
import os
16+
import platform
17+
import subprocess
1518

1619
from PyQt5.QtCore import QSettings, QTextCodec, QObject, pyqtSignal
1720

@@ -29,6 +32,31 @@ def qBound(miv, cv, mxv):
2932
return max(min(cv, mxv), miv)
3033

3134

35+
def openFolder(path):
36+
"""打开文件夹
37+
:param path: 文件/文件夹
38+
"""
39+
system = platform.system()
40+
if system.startswith('Window'):
41+
try:
42+
path = path.replace('/', '\\')
43+
ctypes.windll.ole32.CoInitialize(None)
44+
pidl = ctypes.windll.shell32.ILCreateFromPathW(path)
45+
ctypes.windll.shell32.SHOpenFolderAndSelectItems(
46+
pidl, 0, None, 0)
47+
ctypes.windll.shell32.ILFree(pidl)
48+
ctypes.windll.ole32.CoUninitialize()
49+
except:
50+
path = os.path.dirname(path).replace('/', '\\')
51+
subprocess.call(['explorer', path])
52+
elif system.startswith('Darwin'):
53+
path = os.path.dirname(path).replace('\\', '/')
54+
subprocess.call(['open', path])
55+
else:
56+
path = os.path.dirname(path).replace('\\', '/')
57+
subprocess.call(['nautilus', path])
58+
59+
3260
def git_blob_hash(path):
3361
"""git方式计算文件sha1
3462
:param path: file path

Utils/ThemeManager.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,12 @@
139139
#buttonPreviewApply:pressed {{
140140
background: rgba({0}, {1}, {2}, 230);
141141
}}
142+
143+
/*菜单*/
144+
QMenu::item:selected {{
145+
color: white;
146+
background: rgba({0}, {1}, {2}, 200);
147+
}}
142148
"""
143149

144150
# 渐变颜色
@@ -246,6 +252,12 @@
246252
#buttonPreviewApply:pressed {{
247253
background: rgba({0}, {1}, {2}, 230);
248254
}}
255+
256+
/*菜单*/
257+
QMenu::item:selected {{
258+
color: white;
259+
background: rgba({0}, {1}, {2}, 200);
260+
}}
249261
"""
250262

251263

Widgets/MainWindow.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ def _initUpdate(self):
8686

8787
def _initCatalog(self):
8888
# 更新目录
89+
self._showNotice('正在更新例子代码')
8990
CloneThread.start()
9091

9192
@pyqtSlot(str)

Widgets/MainWindowBase.py

Lines changed: 87 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,13 @@
1313
import webbrowser
1414

1515
from PyQt5.QtCore import pyqtSlot, QUrl, QLocale, QTranslator
16-
from PyQt5.QtGui import QColor
16+
from PyQt5.QtGui import QColor, QCursor
1717
from PyQt5.QtWebKit import QWebSettings
1818
from PyQt5.QtWebKitWidgets import QWebPage
19-
from PyQt5.QtWidgets import QApplication
19+
from PyQt5.QtWidgets import QApplication, QMenu, QAction
2020

2121
from Utils import Constants
22-
from Utils.CommonUtil import Signals, Setting, AppLog
22+
from Utils.CommonUtil import Signals, Setting, AppLog, openFolder
2323
from Utils.GradientUtils import GradientUtils
2424
from Utils.NetworkAccessManager import NetworkAccessManager
2525
from Utils.ThemeManager import ThemeManager
@@ -86,6 +86,7 @@ def _initSignals(self):
8686
Signals.showReadmed.connect(self.renderReadme)
8787
Signals.urlLoaded.connect(self.onUrlLoaded)
8888
Signals.runExampled.connect(self._runFile)
89+
Signals.cloneFinished.connect(lambda: self._showNotice('更新例子完成'))
8990
Signals.cloneFinished.connect(self.treeViewCatalogs.initCatalog)
9091
Signals.cloneFinished.connect(self.renderReadme)
9192
Signals.progressStoped.connect(self.widgetCatalogs.stop)
@@ -103,6 +104,20 @@ def _initLanguage(self):
103104

104105
def _initWebView(self):
105106
"""初始化网页"""
107+
# 右键菜单
108+
self._webviewMenu = QMenu(self.tr('Menu'), self.webViewContent)
109+
self._webviewactRun = QAction(
110+
self.tr('Run'), self._webviewMenu, triggered=self._doActRun)
111+
self._webviewactView = QAction(
112+
self.tr('View'), self._webviewMenu, triggered=self._doActView)
113+
self._webviewactFolder = QAction(
114+
self.tr('Open'), self._webviewMenu, triggered=self._doActOpen)
115+
self._webviewMenu.addAction(self._webviewactRun)
116+
self._webviewMenu.addAction(self._webviewactView)
117+
self._webviewMenu.addAction(self._webviewactFolder)
118+
119+
self.webViewContent.customContextMenuRequested.connect(
120+
self._showWebMenu)
106121
settings = self.webViewContent.settings()
107122
# 设置默认编码
108123
settings.setDefaultTextEncoding('UTF-8')
@@ -119,6 +134,75 @@ def _initWebView(self):
119134
self.webViewContent.load(QUrl.fromLocalFile(
120135
os.path.abspath(Constants.HomeFile)))
121136

137+
def _doActRun(self):
138+
"""右键菜单运行代码
139+
"""
140+
path = self.sender().data()
141+
Signals.runExampled.emit(path)
142+
143+
def _doActView(self):
144+
"""右键菜单查看代码
145+
"""
146+
path = self.sender().data()
147+
try:
148+
code = open(path, 'rb').read().decode(errors='ignore')
149+
Signals.showCoded.emit(code)
150+
except Exception as e:
151+
AppLog.warn(str(e))
152+
153+
def _doActOpen(self):
154+
"""右键菜单打开文件夹
155+
"""
156+
path = self.sender().data()
157+
openFolder(path)
158+
159+
def _showWebMenu(self, pos):
160+
"""显示网页右键菜单
161+
:param pos: 点击位置
162+
"""
163+
hit = self.webViewContent.page().currentFrame().hitTestContent(pos)
164+
url = hit.linkUrl()
165+
if url.isValid():
166+
path = url.toLocalFile().strip().replace('\\', '/')
167+
names = path.split('Markdown/')
168+
if len(names) == 1:
169+
return
170+
path = os.path.abspath(os.path.join(
171+
Constants.DirCurrent, names[1]))
172+
AppLog.debug('path: {}'.format(path))
173+
AppLog.debug('isdir: {}'.format(os.path.isdir(path)))
174+
self._webviewactRun.setData(path)
175+
self._webviewactView.setData(path)
176+
self._webviewactFolder.setData(path)
177+
if os.path.exists(path) and os.path.isdir(path):
178+
self._webviewactRun.setVisible(False)
179+
self._webviewactView.setVisible(False)
180+
self._webviewactFolder.setVisible(True)
181+
elif os.path.exists(path) and os.path.isfile(path):
182+
self._webviewactRun.setVisible(True)
183+
self._webviewactView.setVisible(True)
184+
self._webviewactFolder.setVisible(True)
185+
self._webviewMenu.exec_(QCursor.pos())
186+
187+
def _showNotice(self, message, timeout=2000):
188+
"""底部显示提示
189+
:param message: 提示消息
190+
"""
191+
if hasattr(self, '_tip'):
192+
self._tip._hideTimer.stop()
193+
self._tip.close()
194+
self._tip.deleteLater()
195+
del self._tip
196+
self._tip = ToolTip()
197+
self._tip.setText(message)
198+
self._tip.show()
199+
self._tip.move(
200+
self.pos().x() + int((self.width() - self._tip.width()) / 2),
201+
self.pos().y() + self.height() - 60,
202+
)
203+
self._tip._hideTimer.timeout.connect(self._tip.close)
204+
self._tip._hideTimer.start(timeout)
205+
122206
@pyqtSlot()
123207
def on_buttonSkin_clicked(self):
124208
"""选择主题样式

0 commit comments

Comments
 (0)