本文整理汇总了Python中PyQt5.QtWidgets.QScrollArea.verticalScrollBar方法的典型用法代码示例。如果您正苦于以下问题:Python QScrollArea.verticalScrollBar方法的具体用法?Python QScrollArea.verticalScrollBar怎么用?Python QScrollArea.verticalScrollBar使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QScrollArea
的用法示例。
在下文中一共展示了QScrollArea.verticalScrollBar方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ConfigurationWidget
# 需要导入模块: from PyQt5.QtWidgets import QScrollArea [as 别名]
# 或者: from PyQt5.QtWidgets.QScrollArea import verticalScrollBar [as 别名]
#.........这里部分代码省略.........
return page
def showConfigurationPageByName(self, pageName, setCurrent=True):
"""
Public slot to show a named configuration page.
@param pageName name of the configuration page to show (string)
@param setCurrent flag indicating to set the current item (boolean)
"""
if pageName == "empty" or pageName not in self.configItems:
page = self.emptyPage
else:
pageData = self.configItems[pageName]
if pageData[-1] is None and pageData[2] is not None:
# the page was not loaded yet, create it
page = self.__initPage(pageData)
else:
page = pageData[-1]
if page is None:
page = self.emptyPage
elif setCurrent:
items = self.configList.findItems(
pageData[0],
Qt.MatchFixedString | Qt.MatchRecursive)
for item in items:
if item.data(0, Qt.UserRole) == pageName:
self.configList.setCurrentItem(item)
self.configStack.setCurrentWidget(page)
ssize = self.scrollArea.size()
if self.scrollArea.horizontalScrollBar():
ssize.setHeight(
ssize.height() -
self.scrollArea.horizontalScrollBar().height() - 2)
if self.scrollArea.verticalScrollBar():
ssize.setWidth(
ssize.width() -
self.scrollArea.verticalScrollBar().width() - 2)
psize = page.minimumSizeHint()
self.configStack.resize(max(ssize.width(), psize.width()),
max(ssize.height(), psize.height()))
if page != self.emptyPage:
page.polishPage()
self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(True)
self.buttonBox.button(QDialogButtonBox.Reset).setEnabled(True)
else:
self.buttonBox.button(QDialogButtonBox.Apply).setEnabled(False)
self.buttonBox.button(QDialogButtonBox.Reset).setEnabled(False)
# reset scrollbars
for sb in [self.scrollArea.horizontalScrollBar(),
self.scrollArea.verticalScrollBar()]:
if sb:
sb.setValue(0)
self.__currentConfigurationPageName = pageName
def getConfigurationPageName(self):
"""
Public method to get the page name of the current page.
@return page name of the current page (string)
"""
return self.__currentConfigurationPageName
def calledFromEric(self):
示例2: GlyphCollectionWidget
# 需要导入模块: from PyQt5.QtWidgets import QScrollArea [as 别名]
# 或者: from PyQt5.QtWidgets.QScrollArea import verticalScrollBar [as 别名]
#.........这里部分代码省略.........
if event.source() == self:
pos = event.posF()
self.currentDropIndex = int(self._columns * (pos.y() // self.squareSize) \
+ (pos.x() + .5*self.squareSize) // self.squareSize)
def pipeDragLeaveEvent(self, event):
self.currentDropIndex = None
def pipeDropEvent(self, event):
# TODO: consider dropping this check, maybe only subclasses should do it
# so as to dispatch but here we presumably don't need it
if event.source() == self:
insert = self.currentDropIndex
newGlyphNames = event.mimeData().text().split(" ")
font = self._glyphs[0].getParent()
# TODO: should glyphOrder change activate font.dirty?
newGlyphs = [font[name] for name in newGlyphNames]
# put all glyphs to be moved to None (deleting them would
# invalidate our insert indexes)
for index, glyph in enumerate(self._glyphs):
if glyph in newGlyphs:
self._glyphs[index] = None
# insert newGlyphs into the list
lst = self._glyphs[:insert]
lst.extend(newGlyphs+self._glyphs[insert:])
self._glyphs = lst
# now, elide None
self.currentDropIndex = None
self.glyphs = [glyph for glyph in self._glyphs if glyph != None]
# TODO: break this down into set width/set square
# TODO: see whether scrollArea gets resizeEvents
def _sizeEvent(self, width, squareSize=None):
sw = self._scrollArea.verticalScrollBar().width() + self._scrollArea.contentsMargins().right()
if squareSize is not None: self.squareSize = squareSize
columns = (width - sw) // self.squareSize
if not columns > 0: return
self._columns = columns
self.adjustSize()
def sizeHint(self):
# Calculate sizeHint with max(height, _scrollArea.height()) because if scrollArea is
# bigger than widget height after an update, we risk leaving old painted content on screen
return QSize(self._columns * self.squareSize,
max(math.ceil(len(self._glyphs) / self._columns) * self.squareSize, self._scrollArea.height()))
def computeCharacterSelected(self):
if self.characterSelectedCallback is None:
return
cnt = len(self.selection)
if cnt == 1:
elem = next(iter(self.selection))
self.characterSelectedCallback(self._glyphs[elem].name)
else:
self.characterSelectedCallback(cnt)
def _arrowKeyPressEvent(self, event):
count = event.count()
key = event.key()
modifiers = event.modifiers()
# TODO: it might be the case that self._lastSelectedCell cannot be None
# when we arrive here whatsoever
if self._lastSelectedCell is not None:
if key == Qt.Key_Up:
delta = -self._columns
elif key == Qt.Key_Down:
示例3: PixmapDiagram
# 需要导入模块: from PyQt5.QtWidgets import QScrollArea [as 别名]
# 或者: from PyQt5.QtWidgets.QScrollArea import verticalScrollBar [as 别名]
#.........这里部分代码省略.........
scrollBar.setValue(int(factor * scrollBar.value()
+ ((factor - 1) * scrollBar.pageStep() / 2)))
def __levelForZoom(self, zoom):
"""
Private method determining the zoom level index given a zoom factor.
@param zoom zoom factor (integer)
@return index of zoom factor (integer)
"""
try:
index = PixmapDiagram.ZoomLevels.index(zoom)
except ValueError:
for index in range(len(PixmapDiagram.ZoomLevels)):
if zoom <= PixmapDiagram.ZoomLevels[index]:
break
return index
def __doZoom(self, value):
"""
Private method to set the zoom value in percent.
@param value zoom value in percent (integer)
"""
oldValue = self.__zoom()
if value != oldValue:
self.pixmapLabel.resize(
value / 100 * self.pixmapLabel.pixmap().size())
factor = value / oldValue
self.__adjustScrollBar(
self.pixmapView.horizontalScrollBar(), factor)
self.__adjustScrollBar(
self.pixmapView.verticalScrollBar(), factor)
self.__zoomWidget.setValue(value)
def __zoomIn(self):
"""
Private method to zoom into the pixmap.
"""
index = self.__levelForZoom(self.__zoom())
if index < len(PixmapDiagram.ZoomLevels) - 1:
self.__doZoom(PixmapDiagram.ZoomLevels[index + 1])
def __zoomOut(self):
"""
Private method to zoom out of the pixmap.
"""
index = self.__levelForZoom(self.__zoom())
if index > 0:
self.__doZoom(PixmapDiagram.ZoomLevels[index - 1])
def __zoomReset(self):
"""
Private method to reset the zoom value.
"""
self.__doZoom(PixmapDiagram.ZoomLevels[PixmapDiagram.ZoomLevelDefault])
def __zoom(self):
"""
Private method to get the current zoom factor in percent.
@return current zoom factor in percent (integer)
"""
return int(self.pixmapLabel.width() /
示例4: PDFAreaSelectorDlg
# 需要导入模块: from PyQt5.QtWidgets import QScrollArea [as 别名]
# 或者: from PyQt5.QtWidgets.QScrollArea import verticalScrollBar [as 别名]
#.........这里部分代码省略.........
self.exitAct = QAction("E&xit", self)
self.exitAct.setShortcut("Ctrl+Q")
self.exitAct.triggered.connect(self.close)
self.zoomInAct = QAction("Zoom &In (25%)", self)
self.zoomInAct.setShortcut("Ctrl++")
self.zoomInAct.setEnabled(False)
self.zoomInAct.triggered.connect(self.zoomIn)
self.zoomOutAct = QAction("Zoom &Out (25%)", self)
self.zoomOutAct.setShortcut("Ctrl+-")
self.zoomOutAct.setEnabled(False)
self.zoomOutAct.triggered.connect(self.zoomOut)
self.normalSizeAct = QAction("&Normal Size", self)
self.normalSizeAct.setShortcut("Ctrl+S")
self.normalSizeAct.setEnabled(False)
self.normalSizeAct.triggered.connect(self.normalSize)
self.fitToWindowAct = QAction("&Fit to Window", self)
self.fitToWindowAct.setEnabled(False)
self.fitToWindowAct.setCheckable(True)
self.fitToWindowAct.setShortcut("Ctrl+F")
self.fitToWindowAct.triggered.connect(self.fitToWindow)
self.nextPageAct = QAction("&Next page", self)
self.nextPageAct.setEnabled(True)
self.nextPageAct.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Right))
self.nextPageAct.triggered.connect(self.nextPage)
self.previousPageAct = QAction("&Previous page", self)
self.previousPageAct.setEnabled(True)
self.previousPageAct.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Left))
self.previousPageAct.triggered.connect(self.previousPage)
def createMenus(self):
self.menuBar = QMenuBar(self)
self.fileMenu = QMenu("&File", self)
self.fileMenu.addAction(self.exitAct)
self.viewMenu = QMenu("&View", self)
self.viewMenu.addAction(self.zoomInAct)
self.viewMenu.addAction(self.zoomOutAct)
self.viewMenu.addAction(self.normalSizeAct)
self.viewMenu.addSeparator()
self.viewMenu.addAction(self.fitToWindowAct)
self.viewMenu.addSeparator()
self.viewMenu.addAction(self.nextPageAct)
self.viewMenu.addAction(self.previousPageAct)
self.menuBar.addMenu(self.fileMenu)
self.menuBar.addMenu(self.viewMenu)
def updateActions(self):
self.zoomInAct.setEnabled(not self.fitToWindowAct.isChecked())
self.zoomOutAct.setEnabled(not self.fitToWindowAct.isChecked())
self.normalSizeAct.setEnabled(not self.fitToWindowAct.isChecked())
def scaleImage(self, factor):
assert(self.imageLabel.pixmap())
self.scaleFactor *= factor
self.imageLabel.resize(self.scaleFactor * self.imageLabel.pixmap().size())
self.adjustScrollBar(self.scrollArea.horizontalScrollBar(), factor)
self.adjustScrollBar(self.scrollArea.verticalScrollBar(), factor)
self.zoomInAct.setEnabled(self.scaleFactor < 3.0)
self.zoomOutAct.setEnabled(self.scaleFactor > 0.333)
def adjustScrollBar(self, scrollBar, factor):
scrollBar.setValue(int(factor * scrollBar.value()
+ ((factor - 1) * scrollBar.pageStep()/2)))
def nextPage(self):
if self._parent.currentPageInd < len(self._parent.pages)-1:
self._parent.currentPageInd += 1
self.loadImage()
self.noPageTxt.setText(str(self._parent.currentPageInd+1))
def previousPage(self):
if self._parent.currentPageInd > 0:
self._parent.currentPageInd -= 1
self.loadImage()
self.noPageTxt.setText(str(self._parent.currentPageInd+1))
示例5: GlyphView
# 需要导入模块: from PyQt5.QtWidgets import QScrollArea [as 别名]
# 或者: from PyQt5.QtWidgets.QScrollArea import verticalScrollBar [as 别名]
#.........这里部分代码省略.........
painter.restore()
def scrollArea(self):
return self._scrollArea
def sizeHint(self):
viewport = self._scrollArea.viewport()
scrollWidth, scrollHeight = viewport.width(), viewport.height()
# pick the width and height
glyphWidth, glyphHeight = self._getGlyphWidthHeight()
glyphWidth = glyphWidth * self._scale
glyphHeight = glyphHeight * self._scale
xOffset = 1000 * 2 * self._scale
yOffset = xOffset
width = glyphWidth + xOffset
height = glyphHeight + yOffset
if scrollWidth > width:
width = scrollWidth
if scrollHeight > height:
height = scrollHeight
# calculate and store the vertical centering offset
self._verticalCenterYBuffer = (height - glyphHeight) / 2.0
return QSize(width, height)
def resizeEvent(self, event):
self.adjustSize()
event.accept()
def showEvent(self, event):
# TODO: use fitScaleBBox and adjust scrollBars accordingly
self.fitScaleMetrics()
self.adjustSize()
hSB = self._scrollArea.horizontalScrollBar()
vSB = self._scrollArea.verticalScrollBar()
hSB.setValue((hSB.minimum() + hSB.maximum()) / 2)
vSB.setValue((vSB.minimum() + vSB.maximum()) / 2)
def wheelEvent(self, event):
if event.modifiers() & Qt.ControlModifier:
factor = pow(1.2, event.angleDelta().y() / 120.0)
pos = event.pos()
# compute new scrollbar position
# http://stackoverflow.com/a/32269574/2037879
oldScale = self._scale
newScale = self._scale * factor
hSB = self._scrollArea.horizontalScrollBar()
vSB = self._scrollArea.verticalScrollBar()
scrollBarPos = QPointF(hSB.value(), vSB.value())
deltaToPos = (self.mapToParent(pos) - self.pos()) / oldScale
delta = deltaToPos * (newScale - oldScale)
# TODO: maybe put out a func that does multiply by default
self.setScale(newScale)
# TODO: maybe merge this in setScale
self.adjustSize()
self.update()
hSB.setValue(scrollBarPos.x() + delta.x())
vSB.setValue(scrollBarPos.y() + delta.y())
event.accept()
else:
super().wheelEvent(event)
# ------------
# Canvas tools
# ------------
# current tool
示例6: ImageViewer
# 需要导入模块: from PyQt5.QtWidgets import QScrollArea [as 别名]
# 或者: from PyQt5.QtWidgets.QScrollArea import verticalScrollBar [as 别名]
#.........这里部分代码省略.........
def createActions(self):
self.openAct = QAction(
QIcon(CURRENT_DIR + '/open.png'),
"&Open...", self, shortcut="Ctrl+O",
triggered=self.open
)
self.printAct = QAction(
QIcon(CURRENT_DIR + '/print.png'),
"&Print...", self, shortcut="Ctrl+P",
enabled=False, triggered=self.print_
)
self.exitAct = QAction(
QIcon(CURRENT_DIR + '/exit24.png'),
"E&xit", self, shortcut="Ctrl+Q",
triggered=self.close
)
self.zoomInAct = QAction(
QIcon(CURRENT_DIR + '/zoom_in.png'),
"Zoom &In (25%)", self, shortcut="Ctrl++",
enabled=False, triggered=self.zoomIn
)
self.zoomOutAct = QAction(
QIcon(CURRENT_DIR + '/zoom_out.png'),
"Zoom &Out (25%)", self, shortcut="Ctrl+-",
enabled=False, triggered=self.zoomOut
)
self.normalSizeAct = QAction(
QIcon(CURRENT_DIR + '/zoom.png'),
"&Normal Size", self, shortcut="Ctrl+S",
enabled=False, triggered=self.normalSize
)
self.fitToWindowAct = QAction(
QIcon(CURRENT_DIR + '/expand.png'),
"&Fit to Window",
self,
enabled=False,
checkable=True,
shortcut="Ctrl+F",
triggered=self.fitToWindow
)
self.aboutAct = QAction(
QIcon(CURRENT_DIR + '/info.png'),
"&About", self, triggered=self.about
)
self.aboutQtAct = QAction(
QIcon(CURRENT_DIR + '/pyqt.png'),
"About &Qt", self,
triggered=QApplication.instance().aboutQt
)
def createMenus(self):
self.fileMenu = QMenu("&File", self)
self.fileMenu.addAction(self.openAct)
self.fileMenu.addAction(self.printAct)
self.fileMenu.addSeparator()
self.fileMenu.addAction(self.exitAct)
self.viewMenu = QMenu("&View", self)
self.viewMenu.addAction(self.zoomInAct)
self.viewMenu.addAction(self.zoomOutAct)
self.viewMenu.addAction(self.normalSizeAct)
self.viewMenu.addSeparator()
self.viewMenu.addAction(self.fitToWindowAct)
self.helpMenu = QMenu("&Help", self)
self.helpMenu.addAction(self.aboutAct)
self.helpMenu.addAction(self.aboutQtAct)
self.menuBar().addMenu(self.fileMenu)
self.menuBar().addMenu(self.viewMenu)
self.menuBar().addMenu(self.helpMenu)
def updateActions(self):
self.zoomInAct.setEnabled(not self.fitToWindowAct.isChecked())
self.zoomOutAct.setEnabled(not self.fitToWindowAct.isChecked())
self.normalSizeAct.setEnabled(not self.fitToWindowAct.isChecked())
def scaleImage(self, factor):
self.scaleFactor *= factor
self.imageLabel.resize(self.scaleFactor
* self.imageLabel.pixmap().size())
self.adjustScrollBar(self.scrollArea.horizontalScrollBar(), factor)
self.adjustScrollBar(self.scrollArea.verticalScrollBar(), factor)
self.zoomInAct.setEnabled(self.scaleFactor < 3.0)
self.zoomOutAct.setEnabled(self.scaleFactor > 0.333)
def adjustScrollBar(self, scrollBar, factor):
scrollBar.setValue(int(factor * scrollBar.value()
+ ((factor - 1) * scrollBar.pageStep()/2)))
示例7: GlyphsCanvas
# 需要导入模块: from PyQt5.QtWidgets import QScrollArea [as 别名]
# 或者: from PyQt5.QtWidgets.QScrollArea import verticalScrollBar [as 别名]
class GlyphsCanvas(QWidget):
def __init__(self, font, glyphs, pointSize=defaultPointSize, parent=None):
super(GlyphsCanvas, self).__init__(parent)
# XXX: make canvas font-agnostic as in defconAppkit and use
# glyph.getParent() instead
self.font = font
self.fetchFontMetrics()
self.glyphs = glyphs
self.ptSize = pointSize
self.calculateScale()
self.padding = 10
self._showKerning = False
self._showMetrics = False
self._verticalFlip = False
self._lineHeight = 1.1
self._positions = None
self._selected = None
self.doubleClickCallback = None
self.pointSizeChangedCallback = None
self.selectionChangedCallback = None
self._wrapLines = True
self._scrollArea = QScrollArea(self.parent())
self._scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self._scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self._scrollArea.setWidget(self)
self.resize(581, 400)
def scrollArea(self):
return self._scrollArea
def calculateScale(self):
scale = self.ptSize / self.upm
if scale < 0.01:
scale = 0.01
self.scale = scale
def setShowKerning(self, showKerning):
self._showKerning = showKerning
self.update()
def setShowMetrics(self, showMetrics):
self._showMetrics = showMetrics
self.update()
def setVerticalFlip(self, verticalFlip):
self._verticalFlip = verticalFlip
self.update()
def setLineHeight(self, lineHeight):
self._lineHeight = lineHeight
self.update()
def setWrapLines(self, wrapLines):
if self._wrapLines == wrapLines:
return
self._wrapLines = wrapLines
if self._wrapLines:
sw = self._scrollArea.verticalScrollBar().width() + self._scrollArea.contentsMargins().right()
self.resize(self.parent().parent().parent().width() - sw, self.height())
self._scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self._scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
else:
sh = self._scrollArea.horizontalScrollBar().height() + self._scrollArea.contentsMargins().bottom()
self.resize(self.width(), self.parent().parent().parent().height() - sh)
self._scrollArea.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self._scrollArea.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
self.update()
def fetchFontMetrics(self):
self.ascender = self.font.info.ascender
if self.ascender is None:
self.ascender = 750
self.descender = self.font.info.descender
if self.descender is None:
self.descender = 250
self.upm = self.font.info.unitsPerEm
if self.upm is None or not self.upm > 0:
self.upm = 1000
def setGlyphs(self, newGlyphs):
self.glyphs = newGlyphs
self._selected = None
self.update()
def setPointSize(self, pointSize):
self.ptSize = int(pointSize)
self.calculateScale()
self.update()
def setSelected(self, selected):
self._selected = selected
if self._positions is not None:
cur_len = 0
line = -1
for index, li in enumerate(self._positions):
if cur_len + len(li) > self._selected:
pos, width = li[self._selected - cur_len]
line = index
break
#.........这里部分代码省略.........
示例8: MainWindow
# 需要导入模块: from PyQt5.QtWidgets import QScrollArea [as 别名]
# 或者: from PyQt5.QtWidgets.QScrollArea import verticalScrollBar [as 别名]
class MainWindow(QMainWindow):
def __init__(self, client_socket, process_events_method):
super().__init__()
self.username = config.user["username"]
self.client_socket = client_socket
self.client_socket.recv_message.connect(self.recvMessage)
self.process_events_method = process_events_method
self.chats = {}
self.send_on_enter = True
self.initMenubar()
self.initUI()
for chat in config.chats:
self.createChat(chat, config.chats[chat]["participants"])
def initMenubar(self):
self.createChatAction = QAction("&Create Chat", self)
#self.exitAction.setShortcut("Ctrl+Q")
self.createChatAction.triggered.connect(self.createChat)
self.addFriendAction = QAction("&Add Friend", self)
self.addFriendAction.triggered.connect(self.addFriend)
self.menubar = self.menuBar()
self.chatMenu = self.menubar.addMenu("&Chat")
self.chatMenu.addAction(self.createChatAction)
self.friendMenu = self.menubar.addMenu("&Friend")
self.friendMenu.addAction(self.addFriendAction)
def initUI(self):
self.content = QWidget()
self.hbox = QHBoxLayout(self.content)
self.setCentralWidget(self.content)
self.friend_list = QListWidget()
self.friend_list.itemClicked.connect(self.friendClicked)
self.message_scroll = QScrollArea()
self.message_scroll.setWidgetResizable(True)
#TODO have a setting to disable this
self.message_scroll.verticalScrollBar().rangeChanged.connect(self.scrollBottom)
self.message_input = MessageInput()
self.message_input.sendMessage.connect(self.sendMessage)
self.message_split = QSplitter(Qt.Vertical)
self.message_split.addWidget(self.message_scroll)
self.message_split.addWidget(self.message_input)
self.main_split = QSplitter(Qt.Horizontal)
self.main_split.addWidget(self.friend_list)
self.main_split.addWidget(self.message_split)
self.hbox.addWidget(self.main_split)
self.show()
def addFriend(self, username=None):
if type(username) is bool:
add_friend_dialog = AddFriendDialog(self.client_socket)
add_friend_dialog.exec_()
if add_friend_dialog.selected_user == None:
return
username = add_friend_dialog.selected_user
self.chats[username] = {"participants":[username], "messages":[]}
#TODO we should probably sanatize these to prevent directory manipulation
friend = QListWidgetItem(QIcon(config.ICON_DIR + username + ".png"), username)
self.friend_list.addItem(friend)
def createChat(self, chat_name=None, participants=None):
if type(chat_name) is bool:
create_chat_dialog = CreateChatDialog()
create_chat_dialog.exec_()
if not create_chat_dialog.created_chat:
return
chat_name = create_chat_dialog.chat_name
participants = create_chat_dialog.participants
self.chats[chat_name] = {"participants":participants, "messages":[]}
self.friend_list.addItem(QListWidgetItem(chat_name))
def friendClicked(self, item):
self.loadMessages(str(item.text()))
def loadMessages(self, chat):
#self.clearMessages()
#TODO make the message history look pretty
#TODO consider storing a message history for each chat and switch between when needed
#TODO create a chat class and store the chat name as well as the participants there
#TODO index message histories by chat name
self.message_history = QVBoxLayout()
self.message_history.setSpacing(0)
self.message_history.setContentsMargins(0,0,0,0)
self.message_history.insertStretch(-1, 1)
self.message_history_container = QWidget()
self.message_history_container.setLayout(self.message_history)
self.message_scroll.setWidget(self.message_history_container)
#.........这里部分代码省略.........
示例9: ImageViewer
# 需要导入模块: from PyQt5.QtWidgets import QScrollArea [as 别名]
# 或者: from PyQt5.QtWidgets.QScrollArea import verticalScrollBar [as 别名]
#.........这里部分代码省略.........
self.scaleImage(1.25)
def zoomOut(self):
self.scaleImage(0.8)
def normalSize(self):
self.imageLabel.adjustSize()
self.scaleFactor = 1.0
def fitToWindow(self):
fitToWindow = self.fitToWindowAct.isChecked()
self.scrollArea.setWidgetResizable(fitToWindow)
if not fitToWindow:
self.normalSize()
self.updateActions()
def about(self):
QMessageBox.about(self, "About Image Viewer",
"<p>The <b>Image Viewer</b> example shows how to combine "
"QLabel and QScrollArea to display an image. QLabel is "
"typically used for displaying text, but it can also display "
"an image. QScrollArea provides a scrolling view around "
"another widget. If the child widget exceeds the size of the "
"frame, QScrollArea automatically provides scroll bars.</p>"
"<p>The example demonstrates how QLabel's ability to scale "
"its contents (QLabel.scaledContents), and QScrollArea's "
"ability to automatically resize its contents "
"(QScrollArea.widgetResizable), can be used to implement "
"zooming and scaling features.</p>"
"<p>In addition the example shows how to use QPainter to "
"print an image.</p>")
def createActions(self):
self.openAct = QAction("&Open...", self, shortcut="Ctrl+O",
triggered=self.open)
self.printAct = QAction("&Print...", self, shortcut="Ctrl+P",
enabled=False, triggered=self.print_)
self.exitAct = QAction("E&xit", self, shortcut="Ctrl+Q",
triggered=self.close)
self.zoomInAct = QAction("Zoom &In (25%)", self, shortcut="Ctrl++",
enabled=False, triggered=self.zoomIn)
self.zoomOutAct = QAction("Zoom &Out (25%)", self, shortcut="Ctrl+-",
enabled=False, triggered=self.zoomOut)
self.normalSizeAct = QAction("&Normal Size", self, shortcut="Ctrl+S",
enabled=False, triggered=self.normalSize)
self.fitToWindowAct = QAction("&Fit to Window", self, enabled=False,
checkable=True, shortcut="Ctrl+F", triggered=self.fitToWindow)
self.aboutAct = QAction("&About", self, triggered=self.about)
self.aboutQtAct = QAction("About &Qt", self,
triggered=QApplication.instance().aboutQt)
def createMenus(self):
self.fileMenu = QMenu("&File", self)
self.fileMenu.addAction(self.openAct)
self.fileMenu.addAction(self.printAct)
self.fileMenu.addSeparator()
self.fileMenu.addAction(self.exitAct)
self.viewMenu = QMenu("&View", self)
self.viewMenu.addAction(self.zoomInAct)
self.viewMenu.addAction(self.zoomOutAct)
self.viewMenu.addAction(self.normalSizeAct)
self.viewMenu.addSeparator()
self.viewMenu.addAction(self.fitToWindowAct)
self.helpMenu = QMenu("&Help", self)
self.helpMenu.addAction(self.aboutAct)
self.helpMenu.addAction(self.aboutQtAct)
self.menuBar().addMenu(self.fileMenu)
self.menuBar().addMenu(self.viewMenu)
self.menuBar().addMenu(self.helpMenu)
def updateActions(self):
self.zoomInAct.setEnabled(not self.fitToWindowAct.isChecked())
self.zoomOutAct.setEnabled(not self.fitToWindowAct.isChecked())
self.normalSizeAct.setEnabled(not self.fitToWindowAct.isChecked())
def scaleImage(self, factor):
self.scaleFactor *= factor
self.imageLabel.resize(self.scaleFactor * self.imageLabel.pixmap().size())
self.adjustScrollBar(self.scrollArea.horizontalScrollBar(), factor)
self.adjustScrollBar(self.scrollArea.verticalScrollBar(), factor)
self.zoomInAct.setEnabled(self.scaleFactor < 3.0)
self.zoomOutAct.setEnabled(self.scaleFactor > 0.333)
def adjustScrollBar(self, scrollBar, factor):
scrollBar.setValue(int(factor * scrollBar.value()
+ ((factor - 1) * scrollBar.pageStep()/2)))
示例10: Console
# 需要导入模块: from PyQt5.QtWidgets import QScrollArea [as 别名]
# 或者: from PyQt5.QtWidgets.QScrollArea import verticalScrollBar [as 别名]
class Console(QWidget):
# signals
newPatient = pyqtSignal()
goTo = pyqtSignal([str])
textEmitted = pyqtSignal([str])
def __init__(self, parent):
super().__init__(parent)
self.initConsole()
def initConsole(self):
# vertical layout
verticalBox = QVBoxLayout()
verticalBox.setContentsMargins(QMargins(0, 0, 0, 0))
verticalBox.setSpacing(0)
# output QLabel wrapped in QScrollArea
self.scrollArea = QScrollArea(self)
self.scrollArea.setWidgetResizable(True)
self.consoleOutput = QLabel(self)
self.consoleOutput.setStyleSheet(
"background-color: rgb(50, 50, 50);\
border: none;\
color: white;\
padding: 0;"
)
self.consoleOutput.setWordWrap(True)
self.textEmitted[str].connect(self.printText)
self.scrollArea.setWidget(self.consoleOutput)
# input QLineEdit
self.consoleInput = QLineEdit(self)
self.consoleInput.setStyleSheet(
"background-color: rgb(50, 50, 50); \
border: none;\
color: white;\
padding: 0;"
)
self.consoleInput.setFocus()
self.consoleInput.returnPressed.connect(self.readText)
# adding elements to layout
verticalBox.addWidget(self.scrollArea)
verticalBox.addWidget(self.consoleInput)
# setting layout
self.setLayout(verticalBox)
@pyqtSlot(str)
def readText(self):
"""
Function responsible for retreiving text from QLineEdit
and emitting it
"""
# retreive text
inputText = str(self.consoleInput.text())
# clear QLineEdit
self.consoleInput.setText('')
# if new patient
if inputText == 'Nowy pacjent':
# emit new patient signal
self.newPatient.emit()
elif inputText.split()[0] == 'Idź':
self.goTo.emit(inputText.split(None, 1)[1])
elif inputText != '':
# emit symptoms in signal
self.textEmitted.emit(inputText)
@pyqtSlot(str)
def printText(self, text):
"""
Function responsible for printing text into QLabel
"""
# print text in console
textToPrint = self.consoleOutput.text() + '\n' + text
self.consoleOutput.setText(textToPrint)
# move slider to the bottom
verticalScrollBar = self.scrollArea.verticalScrollBar()
consoleOuputHeight = self.consoleOutput.geometry().height()
verticalScrollBar.setMaximum(consoleOuputHeight)
verticalScrollBar.setValue(verticalScrollBar.maximum())
示例11: SIGNAL
# 需要导入模块: from PyQt5.QtWidgets import QScrollArea [as 别名]
# 或者: from PyQt5.QtWidgets.QScrollArea import verticalScrollBar [as 别名]
exportb.clicked.connect(export)
statsb.clicked.connect(createStats)
else:
push.connect(push, SIGNAL("clicked()"), update)
plotb.connect(plotb, SIGNAL("clicked()"), plot)
toggleb.connect(toggleb, SIGNAL("clicked()"), toggle)
exportb.connect(exportb, SIGNAL("clicked()"), export)
statsb.connect(statsb, SIGNAL("clicked()"), createStats)
guiConfig = {"x": 50, "y": 50, "width": 800, "height": 500, "scrollPosition": 0}
if os.path.exists("gui_config.yml"):
with open("gui_config.yml") as f:
guiConfig.update(yaml.load(f))
window.setGeometry(guiConfig["x"], guiConfig["y"], guiConfig["width"], guiConfig["height"])
area.verticalScrollBar().setValue(guiConfig["scrollPosition"])
window.show()
r = app.exec_()
guiConfig["x"] = window.x()
guiConfig["y"] = window.y()
guiConfig["width"] = window.width()
guiConfig["height"] = window.height()
guiConfig["scrollPosition"] = area.verticalScrollBar().value()
with open("gui_config.yml", "w") as f:
f.write(yaml.dump(guiConfig))
sys.exit(r)
示例12: MainWindow
# 需要导入模块: from PyQt5.QtWidgets import QScrollArea [as 别名]
# 或者: from PyQt5.QtWidgets.QScrollArea import verticalScrollBar [as 别名]
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(100, 100, 500,300)
self.setFixedSize(500,300)
self.setWindowTitle('OFX Date Fix')
self.setAcceptDrops(True)
self.label = QLabel(self)
self.label.setStyleSheet("""
font: 10pt Courier;
background-color: white;
""")
self.label.setText('Drag & drop OFX/CSV pair here')
self.label.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft)
self.scrollArea = QScrollArea(self)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.verticalScrollBar().rangeChanged.connect(self.resizeScroll)
self.scrollArea.setWidget(self.label)
self.setCentralWidget(self.scrollArea)
self.show()
def dragEnterEvent(self, e):
e.accept()
urls = []
if e.mimeData().hasUrls:
for url in e.mimeData().urls():
urls.append(str(url.toLocalFile()))
if len(urls) == 2:
if urls[0][-4:] == '.ofx' and urls[1][-4:] == '.csv':
self.appendText('Drop!')
elif urls[0][-4:] == '.csv' and urls[1][-4:] == '.ofx':
self.appendText('Drop!')
else:
self.appendText('Not a OFX/CSV pair')
else:
self.appendText('Not a pair of files')
else:
self.appendText('Not a file')
def dragLeaveEvent(self, e):
self.appendText('Drag & drop OFX/CSV pair here')
def dropEvent(self, e):
e.accept
urls = []
if e.mimeData().hasUrls:
for url in e.mimeData().urls():
urls.append(str(url.toLocalFile()))
if len(urls) == 2:
if urls[0][-4:] == '.ofx' and urls[1][-4:] == '.csv':
output = replace_dates(urls[0], urls[1])
self.appendText(output)
elif urls[0][-4:] == '.csv' and urls[1][-4:] == '.ofx':
output = replace_dates(urls[1], urls[0])
self.appendText(output)
def appendText(self, text):
self.label.setText(self.label.text() + '\n' + text)
def resizeScroll(self, mini, maxi):
self.scrollArea.verticalScrollBar().setValue(maxi)