src/eric7/Tools/UIPreviewer.py

branch
eric7
changeset 9221
bf71ee032bb4
parent 9209
b99e7fd55fd3
child 9413
80c06d472826
equal deleted inserted replaced
9220:e9e7eca7efee 9221:bf71ee032bb4
11 import pathlib 11 import pathlib
12 12
13 from PyQt6.QtCore import QDir, QEvent, QSize, Qt 13 from PyQt6.QtCore import QDir, QEvent, QSize, Qt
14 from PyQt6.QtGui import QAction, QKeySequence, QImageWriter, QPainter 14 from PyQt6.QtGui import QAction, QKeySequence, QImageWriter, QPainter
15 from PyQt6.QtWidgets import ( 15 from PyQt6.QtWidgets import (
16 QSizePolicy, QSpacerItem, QWidget, QHBoxLayout, QWhatsThis, QDialog, 16 QSizePolicy,
17 QScrollArea, QApplication, QStyleFactory, QFrame, QMainWindow, 17 QSpacerItem,
18 QComboBox, QVBoxLayout, QLabel 18 QWidget,
19 QHBoxLayout,
20 QWhatsThis,
21 QDialog,
22 QScrollArea,
23 QApplication,
24 QStyleFactory,
25 QFrame,
26 QMainWindow,
27 QComboBox,
28 QVBoxLayout,
29 QLabel,
19 ) 30 )
20 from PyQt6.QtPrintSupport import QPrinter, QPrintDialog 31 from PyQt6.QtPrintSupport import QPrinter, QPrintDialog
21 from PyQt6 import uic 32 from PyQt6 import uic
22 33
23 34
33 44
34 class UIPreviewer(EricMainWindow): 45 class UIPreviewer(EricMainWindow):
35 """ 46 """
36 Class implementing the UI Previewer main window. 47 Class implementing the UI Previewer main window.
37 """ 48 """
49
38 def __init__(self, filename=None, parent=None, name=None): 50 def __init__(self, filename=None, parent=None, name=None):
39 """ 51 """
40 Constructor 52 Constructor
41 53
42 @param filename name of a UI file to load 54 @param filename name of a UI file to load
43 @param parent parent widget of this window (QWidget) 55 @param parent parent widget of this window (QWidget)
44 @param name name of this window (string) 56 @param name name of this window (string)
45 """ 57 """
46 self.mainWidget = None 58 self.mainWidget = None
47 self.currentFile = QDir.currentPath() 59 self.currentFile = QDir.currentPath()
48 60
49 super().__init__(parent) 61 super().__init__(parent)
50 if not name: 62 if not name:
51 self.setObjectName("UIPreviewer") 63 self.setObjectName("UIPreviewer")
52 else: 64 else:
53 self.setObjectName(name) 65 self.setObjectName(name)
54 66
55 self.setStyle(Preferences.getUI("Style"), 67 self.setStyle(Preferences.getUI("Style"), Preferences.getUI("StyleSheet"))
56 Preferences.getUI("StyleSheet")) 68
57
58 self.resize(QSize(600, 480).expandedTo(self.minimumSizeHint())) 69 self.resize(QSize(600, 480).expandedTo(self.minimumSizeHint()))
59 self.statusBar() 70 self.statusBar()
60 71
61 self.setWindowIcon(UI.PixmapCache.getIcon("eric")) 72 self.setWindowIcon(UI.PixmapCache.getIcon("eric"))
62 self.setWindowTitle(self.tr("UI Previewer")) 73 self.setWindowTitle(self.tr("UI Previewer"))
63 74
64 self.cw = QWidget(self) 75 self.cw = QWidget(self)
65 self.cw.setObjectName("centralWidget") 76 self.cw.setObjectName("centralWidget")
66 77
67 self.UIPreviewerLayout = QVBoxLayout(self.cw) 78 self.UIPreviewerLayout = QVBoxLayout(self.cw)
68 self.UIPreviewerLayout.setContentsMargins(6, 6, 6, 6) 79 self.UIPreviewerLayout.setContentsMargins(6, 6, 6, 6)
69 self.UIPreviewerLayout.setSpacing(6) 80 self.UIPreviewerLayout.setSpacing(6)
70 self.UIPreviewerLayout.setObjectName("UIPreviewerLayout") 81 self.UIPreviewerLayout.setObjectName("UIPreviewerLayout")
71 82
82 self.styleCombo.setObjectName("styleCombo") 93 self.styleCombo.setObjectName("styleCombo")
83 self.styleCombo.setEditable(False) 94 self.styleCombo.setEditable(False)
84 self.styleCombo.setToolTip(self.tr("Select the GUI Theme")) 95 self.styleCombo.setToolTip(self.tr("Select the GUI Theme"))
85 self.styleLayout.addWidget(self.styleCombo) 96 self.styleLayout.addWidget(self.styleCombo)
86 self.styleCombo.addItems(sorted(QStyleFactory().keys())) 97 self.styleCombo.addItems(sorted(QStyleFactory().keys()))
87 currentStyle = Preferences.getSettings().value('UIPreviewer/style') 98 currentStyle = Preferences.getSettings().value("UIPreviewer/style")
88 if currentStyle is not None: 99 if currentStyle is not None:
89 self.styleCombo.setCurrentIndex(int(currentStyle)) 100 self.styleCombo.setCurrentIndex(int(currentStyle))
90 101
91 styleSpacer = QSpacerItem( 102 styleSpacer = QSpacerItem(
92 40, 20, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum) 103 40, 20, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum
104 )
93 self.styleLayout.addItem(styleSpacer) 105 self.styleLayout.addItem(styleSpacer)
94 self.UIPreviewerLayout.addLayout(self.styleLayout) 106 self.UIPreviewerLayout.addLayout(self.styleLayout)
95 107
96 self.previewSV = QScrollArea(self.cw) 108 self.previewSV = QScrollArea(self.cw)
97 self.previewSV.setObjectName("preview") 109 self.previewSV.setObjectName("preview")
98 self.previewSV.setFrameShape(QFrame.Shape.NoFrame) 110 self.previewSV.setFrameShape(QFrame.Shape.NoFrame)
99 self.previewSV.setFrameShadow(QFrame.Shadow.Plain) 111 self.previewSV.setFrameShadow(QFrame.Shadow.Plain)
100 self.previewSV.setSizePolicy( 112 self.previewSV.setSizePolicy(
101 QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) 113 QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding
114 )
102 self.UIPreviewerLayout.addWidget(self.previewSV) 115 self.UIPreviewerLayout.addWidget(self.previewSV)
103 116
104 self.setCentralWidget(self.cw) 117 self.setCentralWidget(self.cw)
105 118
106 self.styleCombo.activated[int].connect(self.__guiStyleSelected) 119 self.styleCombo.activated[int].connect(self.__guiStyleSelected)
107 120
108 self.__initActions() 121 self.__initActions()
109 self.__initMenus() 122 self.__initMenus()
110 self.__initToolbars() 123 self.__initToolbars()
111 124
112 self.__updateActions() 125 self.__updateActions()
113 126
114 # defere loading of a UI file until we are shown 127 # defere loading of a UI file until we are shown
115 self.fileToLoad = filename 128 self.fileToLoad = filename
116 129
117 def show(self): 130 def show(self):
118 """ 131 """
119 Public slot to show this dialog. 132 Public slot to show this dialog.
120 133
121 This overloaded slot loads a UI file to be previewed after 134 This overloaded slot loads a UI file to be previewed after
122 the main window has been shown. This way, previewing a dialog 135 the main window has been shown. This way, previewing a dialog
123 doesn't interfere with showing the main window. 136 doesn't interfere with showing the main window.
124 """ 137 """
125 super().show() 138 super().show()
126 if self.fileToLoad is not None: 139 if self.fileToLoad is not None:
127 fn, self.fileToLoad = (self.fileToLoad, None) 140 fn, self.fileToLoad = (self.fileToLoad, None)
128 self.__loadFile(fn) 141 self.__loadFile(fn)
129 142
130 def __initActions(self): 143 def __initActions(self):
131 """ 144 """
132 Private method to define the user interface actions. 145 Private method to define the user interface actions.
133 """ 146 """
134 self.openAct = QAction( 147 self.openAct = QAction(
135 UI.PixmapCache.getIcon("openUI"), 148 UI.PixmapCache.getIcon("openUI"), self.tr("&Open File"), self
136 self.tr('&Open File'), self) 149 )
137 self.openAct.setShortcut( 150 self.openAct.setShortcut(QKeySequence(self.tr("Ctrl+O", "File|Open")))
138 QKeySequence(self.tr("Ctrl+O", "File|Open"))) 151 self.openAct.setStatusTip(self.tr("Open a UI file for display"))
139 self.openAct.setStatusTip(self.tr('Open a UI file for display')) 152 self.openAct.setWhatsThis(
140 self.openAct.setWhatsThis(self.tr( 153 self.tr(
141 """<b>Open File</b>""" 154 """<b>Open File</b>"""
142 """<p>This opens a new UI file for display.</p>""" 155 """<p>This opens a new UI file for display.</p>"""
143 )) 156 )
157 )
144 self.openAct.triggered.connect(self.__openFile) 158 self.openAct.triggered.connect(self.__openFile)
145 159
146 self.printAct = QAction( 160 self.printAct = QAction(
147 UI.PixmapCache.getIcon("print"), 161 UI.PixmapCache.getIcon("print"), self.tr("&Print"), self
148 self.tr('&Print'), self) 162 )
149 self.printAct.setShortcut( 163 self.printAct.setShortcut(QKeySequence(self.tr("Ctrl+P", "File|Print")))
150 QKeySequence(self.tr("Ctrl+P", "File|Print"))) 164 self.printAct.setStatusTip(self.tr("Print a screen capture"))
151 self.printAct.setStatusTip(self.tr('Print a screen capture')) 165 self.printAct.setWhatsThis(
152 self.printAct.setWhatsThis(self.tr( 166 self.tr("""<b>Print</b>""" """<p>Print a screen capture.</p>""")
153 """<b>Print</b>""" 167 )
154 """<p>Print a screen capture.</p>"""
155 ))
156 self.printAct.triggered.connect(self.__printImage) 168 self.printAct.triggered.connect(self.__printImage)
157 169
158 self.printPreviewAct = QAction( 170 self.printPreviewAct = QAction(
159 UI.PixmapCache.getIcon("printPreview"), 171 UI.PixmapCache.getIcon("printPreview"), self.tr("Print Preview"), self
160 self.tr('Print Preview'), self) 172 )
161 self.printPreviewAct.setStatusTip(self.tr( 173 self.printPreviewAct.setStatusTip(self.tr("Print preview a screen capture"))
162 'Print preview a screen capture')) 174 self.printPreviewAct.setWhatsThis(
163 self.printPreviewAct.setWhatsThis(self.tr( 175 self.tr(
164 """<b>Print Preview</b>""" 176 """<b>Print Preview</b>""" """<p>Print preview a screen capture.</p>"""
165 """<p>Print preview a screen capture.</p>""" 177 )
166 )) 178 )
167 self.printPreviewAct.triggered.connect(self.__printPreviewImage) 179 self.printPreviewAct.triggered.connect(self.__printPreviewImage)
168 180
169 self.imageAct = QAction( 181 self.imageAct = QAction(
170 UI.PixmapCache.getIcon("screenCapture"), 182 UI.PixmapCache.getIcon("screenCapture"), self.tr("&Screen Capture"), self
171 self.tr('&Screen Capture'), self) 183 )
172 self.imageAct.setShortcut( 184 self.imageAct.setShortcut(
173 QKeySequence(self.tr("Ctrl+S", "File|Screen Capture"))) 185 QKeySequence(self.tr("Ctrl+S", "File|Screen Capture"))
174 self.imageAct.setStatusTip(self.tr( 186 )
175 'Save a screen capture to an image file')) 187 self.imageAct.setStatusTip(self.tr("Save a screen capture to an image file"))
176 self.imageAct.setWhatsThis(self.tr( 188 self.imageAct.setWhatsThis(
177 """<b>Screen Capture</b>""" 189 self.tr(
178 """<p>Save a screen capture to an image file.</p>""" 190 """<b>Screen Capture</b>"""
179 )) 191 """<p>Save a screen capture to an image file.</p>"""
192 )
193 )
180 self.imageAct.triggered.connect(self.__saveImage) 194 self.imageAct.triggered.connect(self.__saveImage)
181 195
182 self.exitAct = QAction( 196 self.exitAct = QAction(UI.PixmapCache.getIcon("exit"), self.tr("&Quit"), self)
183 UI.PixmapCache.getIcon("exit"), self.tr('&Quit'), self) 197 self.exitAct.setShortcut(QKeySequence(self.tr("Ctrl+Q", "File|Quit")))
184 self.exitAct.setShortcut( 198 self.exitAct.setStatusTip(self.tr("Quit the application"))
185 QKeySequence(self.tr("Ctrl+Q", "File|Quit"))) 199 self.exitAct.setWhatsThis(
186 self.exitAct.setStatusTip(self.tr('Quit the application')) 200 self.tr("""<b>Quit</b>""" """<p>Quit the application.</p>""")
187 self.exitAct.setWhatsThis(self.tr( 201 )
188 """<b>Quit</b>"""
189 """<p>Quit the application.</p>"""
190 ))
191 self.exitAct.triggered.connect(ericApp().closeAllWindows) 202 self.exitAct.triggered.connect(ericApp().closeAllWindows)
192 203
193 self.copyAct = QAction( 204 self.copyAct = QAction(
194 UI.PixmapCache.getIcon("editCopy"), self.tr('&Copy'), self) 205 UI.PixmapCache.getIcon("editCopy"), self.tr("&Copy"), self
195 self.copyAct.setShortcut( 206 )
196 QKeySequence(self.tr("Ctrl+C", "Edit|Copy"))) 207 self.copyAct.setShortcut(QKeySequence(self.tr("Ctrl+C", "Edit|Copy")))
197 self.copyAct.setStatusTip( 208 self.copyAct.setStatusTip(self.tr("Copy screen capture to clipboard"))
198 self.tr('Copy screen capture to clipboard')) 209 self.copyAct.setWhatsThis(
199 self.copyAct.setWhatsThis(self.tr( 210 self.tr("""<b>Copy</b>""" """<p>Copy screen capture to clipboard.</p>""")
200 """<b>Copy</b>""" 211 )
201 """<p>Copy screen capture to clipboard.</p>"""
202 ))
203 self.copyAct.triggered.connect(self.__copyImageToClipboard) 212 self.copyAct.triggered.connect(self.__copyImageToClipboard)
204 213
205 self.whatsThisAct = QAction( 214 self.whatsThisAct = QAction(
206 UI.PixmapCache.getIcon("whatsThis"), 215 UI.PixmapCache.getIcon("whatsThis"), self.tr("&What's This?"), self
207 self.tr('&What\'s This?'), self) 216 )
208 self.whatsThisAct.setShortcut(QKeySequence(self.tr("Shift+F1"))) 217 self.whatsThisAct.setShortcut(QKeySequence(self.tr("Shift+F1")))
209 self.whatsThisAct.setStatusTip(self.tr('Context sensitive help')) 218 self.whatsThisAct.setStatusTip(self.tr("Context sensitive help"))
210 self.whatsThisAct.setWhatsThis(self.tr( 219 self.whatsThisAct.setWhatsThis(
211 """<b>Display context sensitive help</b>""" 220 self.tr(
212 """<p>In What's This? mode, the mouse cursor shows an arrow""" 221 """<b>Display context sensitive help</b>"""
213 """ with a question mark, and you can click on the interface""" 222 """<p>In What's This? mode, the mouse cursor shows an arrow"""
214 """ elements to get a short description of what they do and""" 223 """ with a question mark, and you can click on the interface"""
215 """ how to use them. In dialogs, this feature can be accessed""" 224 """ elements to get a short description of what they do and"""
216 """ using the context help button in the titlebar.</p>""" 225 """ how to use them. In dialogs, this feature can be accessed"""
217 )) 226 """ using the context help button in the titlebar.</p>"""
227 )
228 )
218 self.whatsThisAct.triggered.connect(self.__whatsThis) 229 self.whatsThisAct.triggered.connect(self.__whatsThis)
219 230
220 self.aboutAct = QAction(self.tr('&About'), self) 231 self.aboutAct = QAction(self.tr("&About"), self)
221 self.aboutAct.setStatusTip(self.tr( 232 self.aboutAct.setStatusTip(self.tr("Display information about this software"))
222 'Display information about this software')) 233 self.aboutAct.setWhatsThis(
223 self.aboutAct.setWhatsThis(self.tr( 234 self.tr(
224 """<b>About</b>""" 235 """<b>About</b>"""
225 """<p>Display some information about this software.</p>""" 236 """<p>Display some information about this software.</p>"""
226 )) 237 )
238 )
227 self.aboutAct.triggered.connect(self.__about) 239 self.aboutAct.triggered.connect(self.__about)
228 240
229 self.aboutQtAct = QAction(self.tr('About &Qt'), self) 241 self.aboutQtAct = QAction(self.tr("About &Qt"), self)
230 self.aboutQtAct.setStatusTip( 242 self.aboutQtAct.setStatusTip(
231 self.tr('Display information about the Qt toolkit')) 243 self.tr("Display information about the Qt toolkit")
232 self.aboutQtAct.setWhatsThis(self.tr( 244 )
233 """<b>About Qt</b>""" 245 self.aboutQtAct.setWhatsThis(
234 """<p>Display some information about the Qt toolkit.</p>""" 246 self.tr(
235 )) 247 """<b>About Qt</b>"""
248 """<p>Display some information about the Qt toolkit.</p>"""
249 )
250 )
236 self.aboutQtAct.triggered.connect(self.__aboutQt) 251 self.aboutQtAct.triggered.connect(self.__aboutQt)
237 252
238 def __initMenus(self): 253 def __initMenus(self):
239 """ 254 """
240 Private method to create the menus. 255 Private method to create the menus.
241 """ 256 """
242 mb = self.menuBar() 257 mb = self.menuBar()
243 258
244 menu = mb.addMenu(self.tr('&File')) 259 menu = mb.addMenu(self.tr("&File"))
245 menu.setTearOffEnabled(True) 260 menu.setTearOffEnabled(True)
246 menu.addAction(self.openAct) 261 menu.addAction(self.openAct)
247 menu.addAction(self.imageAct) 262 menu.addAction(self.imageAct)
248 menu.addSeparator() 263 menu.addSeparator()
249 menu.addAction(self.printPreviewAct) 264 menu.addAction(self.printPreviewAct)
250 menu.addAction(self.printAct) 265 menu.addAction(self.printAct)
251 menu.addSeparator() 266 menu.addSeparator()
252 menu.addAction(self.exitAct) 267 menu.addAction(self.exitAct)
253 268
254 menu = mb.addMenu(self.tr("&Edit")) 269 menu = mb.addMenu(self.tr("&Edit"))
255 menu.setTearOffEnabled(True) 270 menu.setTearOffEnabled(True)
256 menu.addAction(self.copyAct) 271 menu.addAction(self.copyAct)
257 272
258 mb.addSeparator() 273 mb.addSeparator()
259 274
260 menu = mb.addMenu(self.tr('&Help')) 275 menu = mb.addMenu(self.tr("&Help"))
261 menu.setTearOffEnabled(True) 276 menu.setTearOffEnabled(True)
262 menu.addAction(self.aboutAct) 277 menu.addAction(self.aboutAct)
263 menu.addAction(self.aboutQtAct) 278 menu.addAction(self.aboutQtAct)
264 menu.addSeparator() 279 menu.addSeparator()
265 menu.addAction(self.whatsThisAct) 280 menu.addAction(self.whatsThisAct)
275 filetb.addSeparator() 290 filetb.addSeparator()
276 filetb.addAction(self.printPreviewAct) 291 filetb.addAction(self.printPreviewAct)
277 filetb.addAction(self.printAct) 292 filetb.addAction(self.printAct)
278 filetb.addSeparator() 293 filetb.addSeparator()
279 filetb.addAction(self.exitAct) 294 filetb.addAction(self.exitAct)
280 295
281 edittb = self.addToolBar(self.tr("Edit")) 296 edittb = self.addToolBar(self.tr("Edit"))
282 edittb.setIconSize(UI.Config.ToolBarIconSize) 297 edittb.setIconSize(UI.Config.ToolBarIconSize)
283 edittb.addAction(self.copyAct) 298 edittb.addAction(self.copyAct)
284 299
285 helptb = self.addToolBar(self.tr("Help")) 300 helptb = self.addToolBar(self.tr("Help"))
286 helptb.setIconSize(UI.Config.ToolBarIconSize) 301 helptb.setIconSize(UI.Config.ToolBarIconSize)
287 helptb.addAction(self.whatsThisAct) 302 helptb.addAction(self.whatsThisAct)
288 303
289 def __whatsThis(self): 304 def __whatsThis(self):
290 """ 305 """
291 Private slot called in to enter Whats This mode. 306 Private slot called in to enter Whats This mode.
292 """ 307 """
293 QWhatsThis.enterWhatsThisMode() 308 QWhatsThis.enterWhatsThisMode()
294 309
295 def __guiStyleSelected(self, index): 310 def __guiStyleSelected(self, index):
296 """ 311 """
297 Private slot to handle the selection of a GUI style. 312 Private slot to handle the selection of a GUI style.
298 313
299 @param index index of the selected entry 314 @param index index of the selected entry
300 @type int 315 @type int
301 """ 316 """
302 selectedStyle = self.styleCombo.itemText(index) 317 selectedStyle = self.styleCombo.itemText(index)
303 if self.mainWidget: 318 if self.mainWidget:
304 self.__updateChildren(selectedStyle) 319 self.__updateChildren(selectedStyle)
305 320
306 def __about(self): 321 def __about(self):
307 """ 322 """
308 Private slot to show the about information. 323 Private slot to show the about information.
309 """ 324 """
310 EricMessageBox.about( 325 EricMessageBox.about(
313 self.tr( 328 self.tr(
314 """<h3> About UI Previewer </h3>""" 329 """<h3> About UI Previewer </h3>"""
315 """<p>The UI Previewer loads and displays Qt User-Interface""" 330 """<p>The UI Previewer loads and displays Qt User-Interface"""
316 """ files with various styles, which are selectable via a""" 331 """ files with various styles, which are selectable via a"""
317 """ selection list.</p>""" 332 """ selection list.</p>"""
318 ) 333 ),
319 ) 334 )
320 335
321 def __aboutQt(self): 336 def __aboutQt(self):
322 """ 337 """
323 Private slot to show info about Qt. 338 Private slot to show info about Qt.
324 """ 339 """
325 EricMessageBox.aboutQt(self, self.tr("UI Previewer")) 340 EricMessageBox.aboutQt(self, self.tr("UI Previewer"))
330 """ 345 """
331 fn = EricFileDialog.getOpenFileName( 346 fn = EricFileDialog.getOpenFileName(
332 self, 347 self,
333 self.tr("Select UI file"), 348 self.tr("Select UI file"),
334 self.currentFile, 349 self.currentFile,
335 self.tr("Qt User-Interface Files (*.ui)")) 350 self.tr("Qt User-Interface Files (*.ui)"),
351 )
336 if fn: 352 if fn:
337 self.__loadFile(fn) 353 self.__loadFile(fn)
338 354
339 def __loadFile(self, fn): 355 def __loadFile(self, fn):
340 """ 356 """
341 Private slot to load a ui file. 357 Private slot to load a ui file.
342 358
343 @param fn name of the ui file to be laoded 359 @param fn name of the ui file to be laoded
344 @type str 360 @type str
345 """ 361 """
346 if self.mainWidget: 362 if self.mainWidget:
347 self.mainWidget.close() 363 self.mainWidget.close()
348 self.previewSV.takeWidget() 364 self.previewSV.takeWidget()
349 del self.mainWidget 365 del self.mainWidget
350 self.mainWidget = None 366 self.mainWidget = None
351 367
352 # load the file 368 # load the file
353 with contextlib.suppress(Exception): 369 with contextlib.suppress(Exception):
354 self.mainWidget = uic.loadUi(fn) 370 self.mainWidget = uic.loadUi(fn)
355 371
356 if self.mainWidget: 372 if self.mainWidget:
357 self.currentFile = fn 373 self.currentFile = fn
358 self.__updateChildren(self.styleCombo.currentText()) 374 self.__updateChildren(self.styleCombo.currentText())
359 if isinstance(self.mainWidget, (QDialog, QMainWindow)): 375 if isinstance(self.mainWidget, (QDialog, QMainWindow)):
360 self.mainWidget.show() 376 self.mainWidget.show()
364 self.mainWidget.show() 380 self.mainWidget.show()
365 else: 381 else:
366 EricMessageBox.warning( 382 EricMessageBox.warning(
367 self, 383 self,
368 self.tr("Load UI File"), 384 self.tr("Load UI File"),
369 self.tr( 385 self.tr("""<p>The file <b>{0}</b> could not be loaded.</p>""").format(
370 """<p>The file <b>{0}</b> could not be loaded.</p>""") 386 fn
371 .format(fn)) 387 ),
388 )
372 self.__updateActions() 389 self.__updateActions()
373 390
374 def __updateChildren(self, sstyle): 391 def __updateChildren(self, sstyle):
375 """ 392 """
376 Private slot to change the style of the show UI. 393 Private slot to change the style of the show UI.
377 394
378 @param sstyle name of the selected style (string) 395 @param sstyle name of the selected style (string)
379 """ 396 """
380 with EricOverrideCursor(): 397 with EricOverrideCursor():
381 qstyle = QStyleFactory.create(sstyle) 398 qstyle = QStyleFactory.create(sstyle)
382 self.mainWidget.setStyle(qstyle) 399 self.mainWidget.setStyle(qstyle)
383 400
384 lst = self.mainWidget.findChildren(QWidget) 401 lst = self.mainWidget.findChildren(QWidget)
385 for obj in lst: 402 for obj in lst:
386 with contextlib.suppress(AttributeError): 403 with contextlib.suppress(AttributeError):
387 obj.setStyle(qstyle) 404 obj.setStyle(qstyle)
388 del lst 405 del lst
389 406
390 self.mainWidget.hide() 407 self.mainWidget.hide()
391 self.mainWidget.show() 408 self.mainWidget.show()
392 409
393 self.lastQStyle = qstyle 410 self.lastQStyle = qstyle
394 self.lastStyle = sstyle 411 self.lastStyle = sstyle
395 Preferences.getSettings().setValue( 412 Preferences.getSettings().setValue(
396 'UIPreviewer/style', self.styleCombo.currentIndex()) 413 "UIPreviewer/style", self.styleCombo.currentIndex()
397 414 )
415
398 def __updateActions(self): 416 def __updateActions(self):
399 """ 417 """
400 Private slot to update the actions state. 418 Private slot to update the actions state.
401 """ 419 """
402 if self.mainWidget: 420 if self.mainWidget:
421 if self.mainWidget: 439 if self.mainWidget:
422 self.mainWidget.removeEventFilter(self) 440 self.mainWidget.removeEventFilter(self)
423 del self.mainWidget 441 del self.mainWidget
424 self.mainWidget = None 442 self.mainWidget = None
425 self.__updateActions() 443 self.__updateActions()
426 444
427 def eventFilter(self, obj, ev): 445 def eventFilter(self, obj, ev):
428 """ 446 """
429 Public method called to filter an event. 447 Public method called to filter an event.
430 448
431 @param obj object, that generated the event (QObject) 449 @param obj object, that generated the event (QObject)
432 @param ev the event, that was generated by object (QEvent) 450 @param ev the event, that was generated by object (QEvent)
433 @return flag indicating if event was filtered out 451 @return flag indicating if event was filtered out
434 """ 452 """
435 if obj == self.mainWidget: 453 if obj == self.mainWidget:
441 return QDialog.eventFilter(self, obj, ev) 459 return QDialog.eventFilter(self, obj, ev)
442 elif isinstance(self.mainWidget, QMainWindow): 460 elif isinstance(self.mainWidget, QMainWindow):
443 return QMainWindow.eventFilter(self, obj, ev) 461 return QMainWindow.eventFilter(self, obj, ev)
444 else: 462 else:
445 return False 463 return False
446 464
447 def __saveImage(self): 465 def __saveImage(self):
448 """ 466 """
449 Private slot to handle the Save Image menu action. 467 Private slot to handle the Save Image menu action.
450 """ 468 """
451 if self.mainWidget is None: 469 if self.mainWidget is None:
452 EricMessageBox.critical( 470 EricMessageBox.critical(
453 self, 471 self, self.tr("Save Image"), self.tr("""There is no UI file loaded.""")
454 self.tr("Save Image"), 472 )
455 self.tr("""There is no UI file loaded."""))
456 return 473 return
457 474
458 defaultExt = "PNG" 475 defaultExt = "PNG"
459 filters = "" 476 filters = ""
460 formats = QImageWriter.supportedImageFormats() 477 formats = QImageWriter.supportedImageFormats()
461 for imageFormat in formats: 478 for imageFormat in formats:
462 filters = "{0}*.{1} ".format( 479 filters = "{0}*.{1} ".format(filters, bytes(imageFormat).decode().lower())
463 filters, bytes(imageFormat).decode().lower())
464 fileFilter = self.tr("Images ({0})").format(filters[:-1]) 480 fileFilter = self.tr("Images ({0})").format(filters[:-1])
465 481
466 fname = EricFileDialog.getSaveFileName( 482 fname = EricFileDialog.getSaveFileName(
467 self, 483 self, self.tr("Save Image"), "", fileFilter
468 self.tr("Save Image"), 484 )
469 "",
470 fileFilter)
471 if not fname: 485 if not fname:
472 return 486 return
473 487
474 fpath = pathlib.Path(fname) 488 fpath = pathlib.Path(fname)
475 ext = fpath.suffix.upper().replace(".", "") 489 ext = fpath.suffix.upper().replace(".", "")
476 if not ext: 490 if not ext:
477 ext = defaultExt 491 ext = defaultExt
478 fpath = fpath.with_suffix(".{0}".format(defaultExt.lower())) 492 fpath = fpath.with_suffix(".{0}".format(defaultExt.lower()))
479 493
480 pix = self.mainWidget.grab() 494 pix = self.mainWidget.grab()
481 self.__updateChildren(self.lastStyle) 495 self.__updateChildren(self.lastStyle)
482 if not pix.save(str(fpath), str(ext)): 496 if not pix.save(str(fpath), str(ext)):
483 EricMessageBox.critical( 497 EricMessageBox.critical(
484 self, 498 self,
485 self.tr("Save Image"), 499 self.tr("Save Image"),
486 self.tr( 500 self.tr("""<p>The file <b>{0}</b> could not be saved.</p>""").format(
487 """<p>The file <b>{0}</b> could not be saved.</p>""") 501 fpath
488 .format(fpath)) 502 ),
503 )
489 504
490 def __copyImageToClipboard(self): 505 def __copyImageToClipboard(self):
491 """ 506 """
492 Private slot to handle the Copy Image menu action. 507 Private slot to handle the Copy Image menu action.
493 """ 508 """
494 if self.mainWidget is None: 509 if self.mainWidget is None:
495 EricMessageBox.critical( 510 EricMessageBox.critical(
496 self, 511 self, self.tr("Save Image"), self.tr("""There is no UI file loaded.""")
497 self.tr("Save Image"), 512 )
498 self.tr("""There is no UI file loaded."""))
499 return 513 return
500 514
501 cb = QApplication.clipboard() 515 cb = QApplication.clipboard()
502 cb.setPixmap(self.mainWidget.grab()) 516 cb.setPixmap(self.mainWidget.grab())
503 self.__updateChildren(self.lastStyle) 517 self.__updateChildren(self.lastStyle)
504 518
505 def __printImage(self): 519 def __printImage(self):
506 """ 520 """
507 Private slot to handle the Print Image menu action. 521 Private slot to handle the Print Image menu action.
508 """ 522 """
509 if self.mainWidget is None: 523 if self.mainWidget is None:
510 EricMessageBox.critical( 524 EricMessageBox.critical(
511 self, 525 self, self.tr("Print Image"), self.tr("""There is no UI file loaded.""")
512 self.tr("Print Image"), 526 )
513 self.tr("""There is no UI file loaded."""))
514 return 527 return
515 528
516 settings = Preferences.getSettings() 529 settings = Preferences.getSettings()
517 printer = QPrinter(QPrinter.PrinterMode.HighResolution) 530 printer = QPrinter(QPrinter.PrinterMode.HighResolution)
518 printer.setFullPage(True) 531 printer.setFullPage(True)
519 532
520 printerName = Preferences.getPrinter("UIPreviewer/printername") 533 printerName = Preferences.getPrinter("UIPreviewer/printername")
521 if printerName: 534 if printerName:
522 printer.setPrinterName(printerName) 535 printer.setPrinterName(printerName)
523 printer.setPageSize( 536 printer.setPageSize(
524 QPrinter.PageSize(int(settings.value("UIPreviewer/pagesize")))) 537 QPrinter.PageSize(int(settings.value("UIPreviewer/pagesize")))
538 )
525 printer.setPageOrder( 539 printer.setPageOrder(
526 QPrinter.PageOrder(int(settings.value("UIPreviewer/pageorder")))) 540 QPrinter.PageOrder(int(settings.value("UIPreviewer/pageorder")))
527 printer.setOrientation(QPrinter.Orientation( 541 )
528 int(settings.value("UIPreviewer/orientation")))) 542 printer.setOrientation(
543 QPrinter.Orientation(int(settings.value("UIPreviewer/orientation")))
544 )
529 printer.setColorMode( 545 printer.setColorMode(
530 QPrinter.ColorMode(int(settings.value("UIPreviewer/colormode")))) 546 QPrinter.ColorMode(int(settings.value("UIPreviewer/colormode")))
531 547 )
548
532 printDialog = QPrintDialog(printer, self) 549 printDialog = QPrintDialog(printer, self)
533 if printDialog.exec() == QDialog.DialogCode.Accepted: 550 if printDialog.exec() == QDialog.DialogCode.Accepted:
534 self.statusBar().showMessage(self.tr("Printing the image...")) 551 self.statusBar().showMessage(self.tr("Printing the image..."))
535 self.__print(printer) 552 self.__print(printer)
536 553
537 settings.setValue("UIPreviewer/printername", printer.printerName()) 554 settings.setValue("UIPreviewer/printername", printer.printerName())
538 settings.setValue("UIPreviewer/pagesize", printer.pageSize()) 555 settings.setValue("UIPreviewer/pagesize", printer.pageSize())
539 settings.setValue("UIPreviewer/pageorder", printer.pageOrder()) 556 settings.setValue("UIPreviewer/pageorder", printer.pageOrder())
540 settings.setValue("UIPreviewer/orientation", printer.orientation()) 557 settings.setValue("UIPreviewer/orientation", printer.orientation())
541 settings.setValue("UIPreviewer/colormode", printer.colorMode()) 558 settings.setValue("UIPreviewer/colormode", printer.colorMode())
542 559
543 self.statusBar().showMessage( 560 self.statusBar().showMessage(self.tr("Image sent to printer..."), 2000)
544 self.tr("Image sent to printer..."), 2000)
545 561
546 def __printPreviewImage(self): 562 def __printPreviewImage(self):
547 """ 563 """
548 Private slot to handle the Print Preview menu action. 564 Private slot to handle the Print Preview menu action.
549 """ 565 """
550 from PyQt6.QtPrintSupport import QPrintPreviewDialog 566 from PyQt6.QtPrintSupport import QPrintPreviewDialog
551 567
552 if self.mainWidget is None: 568 if self.mainWidget is None:
553 EricMessageBox.critical( 569 EricMessageBox.critical(
554 self, 570 self,
555 self.tr("Print Preview"), 571 self.tr("Print Preview"),
556 self.tr("""There is no UI file loaded.""")) 572 self.tr("""There is no UI file loaded."""),
573 )
557 return 574 return
558 575
559 settings = Preferences.getSettings() 576 settings = Preferences.getSettings()
560 printer = QPrinter(QPrinter.PrinterMode.HighResolution) 577 printer = QPrinter(QPrinter.PrinterMode.HighResolution)
561 printer.setFullPage(True) 578 printer.setFullPage(True)
562 579
563 printerName = Preferences.getPrinter("UIPreviewer/printername") 580 printerName = Preferences.getPrinter("UIPreviewer/printername")
564 if printerName: 581 if printerName:
565 printer.setPrinterName(printerName) 582 printer.setPrinterName(printerName)
566 printer.setPageSize( 583 printer.setPageSize(
567 QPrinter.PageSize(int(settings.value("UIPreviewer/pagesize")))) 584 QPrinter.PageSize(int(settings.value("UIPreviewer/pagesize")))
585 )
568 printer.setPageOrder( 586 printer.setPageOrder(
569 QPrinter.PageOrder(int(settings.value("UIPreviewer/pageorder")))) 587 QPrinter.PageOrder(int(settings.value("UIPreviewer/pageorder")))
570 printer.setOrientation(QPrinter.Orientation( 588 )
571 int(settings.value("UIPreviewer/orientation")))) 589 printer.setOrientation(
590 QPrinter.Orientation(int(settings.value("UIPreviewer/orientation")))
591 )
572 printer.setColorMode( 592 printer.setColorMode(
573 QPrinter.ColorMode(int(settings.value("UIPreviewer/colormode")))) 593 QPrinter.ColorMode(int(settings.value("UIPreviewer/colormode")))
574 594 )
595
575 preview = QPrintPreviewDialog(printer, self) 596 preview = QPrintPreviewDialog(printer, self)
576 preview.paintRequested.connect(self.__print) 597 preview.paintRequested.connect(self.__print)
577 preview.exec() 598 preview.exec()
578 599
579 def __print(self, printer): 600 def __print(self, printer):
580 """ 601 """
581 Private slot to the actual printing. 602 Private slot to the actual printing.
582 603
583 @param printer reference to the printer object (QPrinter) 604 @param printer reference to the printer object (QPrinter)
584 """ 605 """
585 p = QPainter(printer) 606 p = QPainter(printer)
586 marginX = ( 607 marginX = (
587 printer.pageLayout().paintRectPixels(printer.resolution()).x() - 608 printer.pageLayout().paintRectPixels(printer.resolution()).x()
588 printer.pageLayout().fullRectPixels(printer.resolution()).x() 609 - printer.pageLayout().fullRectPixels(printer.resolution()).x()
589 ) // 2 610 ) // 2
590 marginY = ( 611 marginY = (
591 printer.pageLayout().paintRectPixels(printer.resolution()).y() - 612 printer.pageLayout().paintRectPixels(printer.resolution()).y()
592 printer.pageLayout().fullRectPixels(printer.resolution()).y() 613 - printer.pageLayout().fullRectPixels(printer.resolution()).y()
593 ) // 2 614 ) // 2
594 615
595 # double the margin on bottom of page 616 # double the margin on bottom of page
596 if printer.orientation() == QPrinter.Orientation.Portrait: 617 if printer.orientation() == QPrinter.Orientation.Portrait:
597 width = printer.width() - marginX * 2 618 width = printer.width() - marginX * 2
601 width = printer.width() - marginX * 2 622 width = printer.width() - marginX * 2
602 height = printer.height() - marginY * 2 623 height = printer.height() - marginY * 2
603 img = self.mainWidget.grab().toImage() 624 img = self.mainWidget.grab().toImage()
604 self.__updateChildren(self.lastStyle) 625 self.__updateChildren(self.lastStyle)
605 p.drawImage( 626 p.drawImage(
606 marginX, marginY, img.scaled( 627 marginX,
607 width, height, 628 marginY,
629 img.scaled(
630 width,
631 height,
608 Qt.AspectRatioMode.KeepAspectRatio, 632 Qt.AspectRatioMode.KeepAspectRatio,
609 Qt.TransformationMode.SmoothTransformation 633 Qt.TransformationMode.SmoothTransformation,
610 ) 634 ),
611 ) 635 )
612 p.end() 636 p.end()

eric ide

mercurial