I have two buttons (wgtbtnA & wgtbtnB) placed on two different pages (page1 and page2, respectively) inside a parent object (objectName: stackedWidget). My dilemma is this: when I run the code, the arrows don't display in PyQt. Why? How do I alternate from page1 to page2 and vice-versa?
Here is an image of runtime, which conveys what I am asking for:
Qt Designer:
I'd like to keep those small back arrows.
Below is my code:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'stackedWidget.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
import sys
import os
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(512, 304)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.stackedWidget = QtGui.QStackedWidget(self.centralwidget)
self.stackedWidget.setGeometry(QtCore.QRect(150, 60, 161, 121))
self.stackedWidget.setObjectName(_fromUtf8("stackedWidget"))
self.page = QtGui.QWidget()
self.page.setObjectName(_fromUtf8("page"))
self.wgtMainWindow = QtGui.QPushButton(self.page)
self.wgtMainWindow.setGeometry(QtCore.QRect(50, 50, 75, 23))
self.wgtMainWindow.setObjectName(_fromUtf8("wgtMainWindow"))
self.stackedWidget.addWidget(self.page)
self.page_2 = QtGui.QWidget()
self.page_2.setObjectName(_fromUtf8("page_2"))
self.wgtbtnB = QtGui.QPushButton(self.page_2)
self.wgtbtnB.setGeometry(QtCore.QRect(50, 50, 75, 23))
self.wgtbtnB.setObjectName(_fromUtf8("wgtbtnB"))
self.stackedWidget.addWidget(self.page_2)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 512, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.stackedWidget.setCurrentIndex(1)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.wgtMainWindow.setText(_translate("MainWindow", "Widget A", None))
self.wgtbtnB.setText(_translate("MainWindow", "Widget B", None))
class ControlMainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(ControlMainWindow, self).__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
mySW = ControlMainWindow()
mySW.show()
sys.exit(app.exec_())
You could use the buttons to change the page: {your QPushButton}.clicked.connect(lambda: {your QStackedWidget}.setCurrentIndex({another page}))
By Example:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'stackedWidget.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
import sys
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(512, 304)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.stackedWidget = QtGui.QStackedWidget(self.centralwidget)
self.stackedWidget.setGeometry(QtCore.QRect(150, 60, 161, 121))
self.stackedWidget.setObjectName(_fromUtf8("stackedWidget"))
self.page = QtGui.QWidget()
self.page.setObjectName(_fromUtf8("page"))
self.wgtMainWindow = QtGui.QPushButton(self.page)
self.wgtMainWindow.setGeometry(QtCore.QRect(50, 50, 75, 23))
self.wgtMainWindow.setObjectName(_fromUtf8("wgtMainWindow"))
self.stackedWidget.addWidget(self.page)
self.page_2 = QtGui.QWidget()
self.page_2.setObjectName(_fromUtf8("page_2"))
self.wgtbtnB = QtGui.QPushButton(self.page_2)
self.wgtbtnB.setGeometry(QtCore.QRect(50, 50, 75, 23))
self.wgtbtnB.setObjectName(_fromUtf8("wgtbtnB"))
self.stackedWidget.addWidget(self.page_2)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 512, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.stackedWidget.setCurrentIndex(1)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.wgtMainWindow.setText(_translate("MainWindow", "Widget A", None))
self.wgtbtnB.setText(_translate("MainWindow", "Widget B", None))
class ControlMainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(ControlMainWindow, self).__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.wgtbtnB.clicked.connect(lambda : self.ui.stackedWidget.setCurrentIndex(0))
self.ui.wgtMainWindow.clicked.connect(lambda : self.ui.stackedWidget.setCurrentIndex(1))
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
mySW = ControlMainWindow()
mySW.show()
sys.exit(app.exec_())
Start app:
after clicked button:
after clicked another button:
the two arrows you see in the designer ( in your message below) don't carry over to your application, its a function in the designer so you can switch between them easily
To implement your arrows from one screen to the next you just need to propagate those arrows making sure that they appear in each view -- now this can easily be done via code cannot say how difficult it might be in the designer. Here is a example that does something like what you might be wanting.
from sys import exit as sysExit
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Win1Disply(QFrame):
def __init__(self, parent):
QFrame.__init__(self)
self.setFrameShape(QFrame.StyledPanel)
self.setLineWidth(0.2)
# -------
self.Cntnr = QVBoxLayout()
self.Cntnr.addWidget(QTextEdit('This is Window 1 with whatever contents you want'))
self.Win1Btn = QPushButton('>>')
self.Win1Btn.clicked.connect(parent.RightArrow)
self.Cntnr.addWidget(self.Win1Btn)
self.Cntnr.addStretch(1)
# -------
self.setLayout(self.Cntnr)
class Win2Disply(QFrame):
def __init__(self, parent):
QFrame.__init__(self)
self.setFrameShape(QFrame.StyledPanel)
self.setLineWidth(0.2)
# -------
self.Cntnr = QVBoxLayout()
self.Cntnr.addWidget(QTextEdit('This is Window 2 with whatever contents you want'))
self.Win1Btn = QPushButton('>>')
self.Win1Btn.clicked.connect(parent.RightArrow)
self.Cntnr.addWidget(self.Win1Btn)
self.Cntnr.addStretch(1)
# -------
self.setLayout(self.Cntnr)
class OptionButtons(QToolButton):
# Class OptionButtons ("Text", Connector) inherits from QToolButton
def __init__(self, Text, Connector):
QToolButton.__init__(self)
self.setText(Text)
self.setStyleSheet("font: bold;color: blue;height: 55px;width: 55px;")
self.setIconSize(QSize(32,32))
self.clicked.connect(Connector)
############################## Settings Class ##############################
class OptionSettings(QDialog):
def __init__(self, parent):
QDialog.__init__(self, parent)
line = QFrame()
line.setFrameShape(QFrame.HLine)
line.setFrameShadow(QFrame.Sunken)
self.btnWin1 = OptionButtons('Win One', self.ShowWindow1)
self.btnWin2 = OptionButtons('Win Two', self.ShowWindow2)
# Vertical Box for Buttons *************************************
self.UpLeft = QVBoxLayout()
self.UpLeft.addWidget(self.btnWin1)
self.UpLeft.addWidget(self.btnWin2)
self.UpLeft.addStretch(1)
# Display Area on Right
# Widget Flip Display ******************************************
self.UpRite = QHBoxLayout()
self.Contents = QStackedWidget()
self.Contents.addWidget(QTextEdit('Nothing Selected'))
self.Contents.addWidget(Win1Disply(self))
self.Contents.addWidget(Win2Disply(self))
self.Contents.addWidget(QTextEdit('Settings Saved'))
self.Contents.setCurrentIndex(0)
self.UpRite.addWidget(self.Contents)
# Button and Display Area on Top
self.Upper = QHBoxLayout()
self.Upper.addLayout(self.UpLeft)
self.Upper.addLayout(self.UpRite)
# Save and Cancel Area on Bottom
self.btnSave = QPushButton("Save")
self.btnSave.clicked.connect(self.SaveSettings)
self.btnCncl = QPushButton("Cancel")
self.btnCncl.clicked.connect(self.close)
self.Lower = QHBoxLayout()
self.Lower.addStretch(1)
self.Lower.addWidget(self.btnSave)
self.Lower.addWidget(self.btnCncl)
# Entire Options Window Layout
self.OuterBox = QVBoxLayout()
self.OuterBox.addLayout(self.Upper)
self.OuterBox.addLayout(self.Lower)
self.setLayout(self.OuterBox)
self.setWindowTitle('Settings')
#Geometry(Left, Top, Width, Hight)
self.setGeometry(250, 250, 550, 450)
self.setModal(True)
self.exec()
def ShowWindow1(self):
self.Contents.setCurrentIndex(1)
def ShowWindow2(self):
self.Contents.setCurrentIndex(2)
def SaveSettings(self):
self.Contents.setCurrentIndex(3)
def RightArrow(self):
if self.Contents.currentIndex() == 1:
self.Contents.setCurrentIndex(2)
else:
self.Contents.setCurrentIndex(1)
class CenterPanel(QWidget):
def __init__(self, MainWin):
QWidget.__init__(self)
CntrPane = QTextEdit('Center Panel is Placed Here')
hbox = QHBoxLayout(self)
hbox.addWidget(CntrPane)
self.setLayout(hbox)
class MenuToolBar(QDockWidget):
def __init__(self, MainWin):
QDockWidget.__init__(self)
self.MainWin = MainWin
self.MainMenu = MainWin.menuBar()
self.WndowMenu = self.MainMenu.addMenu('Windows')
self.OptnAct = QAction('Options', self)
self.OptnAct.setStatusTip('Open the Options Window')
self.OptnAct.triggered.connect(MainWin.ShowOptions)
self.WndowMenu.addAction(self.OptnAct)
self.InitToolBar(MainWin)
def InitToolBar(self, MainWin):
self.mainToolBar = MainWin.addToolBar("Quick Access")
self.mainToolBar.addAction(self.OptnAct)
class UI_MainWindow(QMainWindow):
def __init__(self):
super(UI_MainWindow, self).__init__()
self.setWindowTitle('Main Window')
# Left, Top, Width, Height
self.setGeometry(200, 200, 550, 550)
self.CenterPane = CenterPanel(self)
self.setCentralWidget(self.CenterPane)
self.MenuToolBar = MenuToolBar(self)
def ShowOptions(self):
self.Options = OptionSettings(self)
if __name__ == '__main__':
MainApp = QApplication([])
MainGui = UI_MainWindow()
MainGui.show()
sysExit(MainApp.exec_())
If you really need arrows in your stacked widget, another solution is to implement your own "Promoted Widget": it allows you to create your design with custom widgets, that might extend the basic widgets provided by Qt. You won't be able to interact with your own implementation in Designer, but you'll get the result once you run your program.
This is the procedure: create your own subclass of the widget you want to extend, define your custom methods or override existing ones (remember that some private methods require a specific return value type, check the documentation).
It's usually better to save the subclass(es) you created in a separate files.
Then, in Designer add the widget you need (in this case, StackedWidget), right click on it and select "Promote to..."; in the dialog that will be shown, type the subclass name you created in the "Promoted class name" field (in the example below, it will be "StackedWidgetWithArrowButtons") and the file that contains it in the "header file" field: it will be treated as a python import, so do not add the trailing ".py" and remember that if you saved it in a subdirectory you'll need the full "module" path, for example "mysubclasses.customstackwidget", if the file is "customstackwidget" in the "mysubclasses" directory.
Save the ui, compile it and run the program.
class StackedWidgetWithArrowButtons(QtWidgets.QStackedWidget):
def __init__(self, *args, **kwargs):
QtWidgets.QStackedWidget.__init__(self, *args, **kwargs)
self.backwardButton = QtWidgets.QToolButton(self)
self.backwardButton.setIcon(self.style().standardIcon(QtWidgets.QStyle.SP_ArrowLeft))
self.backwardButton.setMaximumSize(24, 24)
self.backwardButton.setFocusPolicy(QtCore.Qt.NoFocus)
self.forwardButton = QtWidgets.QToolButton(self)
self.forwardButton.setIcon(self.style().standardIcon(QtWidgets.QStyle.SP_ArrowRight))
self.forwardButton.setMaximumSize(24, 24)
self.forwardButton.setFocusPolicy(QtCore.Qt.NoFocus)
self.currentChanged.connect(self.checkSwitchButtons)
def checkSwitchButtons(self):
self.forwardButton.setEnabled(self.currentIndex() < self.count() - 1)
self.backwardButton.setEnabled(self.currentIndex() > 0)
def addWidget(self, widget):
# this is a private method of QStackedWidget that is called when
# the ui is being built by the program, we just implement it
# to ensure that the buttons are correctly enabled;
# the index *has* to be returned
index = QtWidgets.QStackedWidget.addWidget(self, widget)
self.checkSwitchButtons()
return index
def removeWidget(self, widget):
# not necessary, but in case you want to remove widgets in the
# future, it will check buttons again
index = QtWidgets.QStackedWidget.removeWidget(self, widget)
self.checkSwitchButtons()
return index
def mousePressEvent(self, event):
# due to the way QStackedWidget is implemented, children widgets
# that are not in its layout might not receive mouse events,
# but we just need to track clicks so this is enough
if event.button() == QtCore.Qt.LeftButton:
if event.pos() in self.backwardButton.geometry():
self.setCurrentIndex(self.currentIndex() - 1)
elif event.pos() in self.forwardButton.geometry():
self.setCurrentIndex(self.currentIndex() + 1)
def resizeEvent(self, event):
# the base class resizeEvent *has* to be called, otherwise
# you could encounter problems with children widgets
QtWidgets.QStackedWidget.resizeEvent(self, event)
# now ensure that the buttons are always placed on the top
# right corner; this positioning is completely manual and you
# have to take button sizes in consideration to avoid
# overlapping buttons; obviously you can place them wherever
# you want.
self.forwardButton.move(self.rect().right() - self.forwardButton.width(), 0)
self.backwardButton.move(self.forwardButton.x() - self.backwardButton.width(), 0)
If you don't want buttons (or you don't like the way they appear) you could implement your own paintEvent. In this case I created small triangles using QPolygons.
class StackedWidgetWithTriangles(QtWidgets.QStackedWidget):
def __init__(self, *args, **kwargs):
QtWidgets.QStackedWidget.__init__(self, *args, **kwargs)
self.backwardRect = QtCore.QRect(0, 0, 16, 16)
self.forwardRect = QtCore.QRect(0, 0, 16, 16)
self.forwardArrow = QtGui.QPolygon([QtCore.QPoint(-6, -6), QtCore.QPoint(6, 0), QtCore.QPoint(-6, 6)])
self.backwardArrow = QtGui.QPolygon([QtCore.QPoint(6, -6), QtCore.QPoint(-6, 0), QtCore.QPoint(6, 6)])
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
if event.pos() in self.backwardRect:
self.setCurrentIndex(self.currentIndex() - 1)
elif event.pos() in self.forwardRect:
self.setCurrentIndex(self.currentIndex() + 1)
def resizeEvent(self, event):
QtWidgets.QStackedWidget.resizeEvent(self, event)
self.forwardRect.moveLeft(self.rect().right() - self.forwardRect.width())
self.backwardRect.moveLeft(self.forwardRect.x() - self.forwardRect.width())
def paintEvent(self, event):
qp = QtGui.QPainter(self)
qp.setRenderHints(qp.Antialiasing)
# set colors according to the possibility of going back or forward,
# showing a "disabled" arrow whenever it's not possible
if self.currentIndex() > 0:
qp.setPen(QtCore.Qt.darkGray)
qp.setBrush(QtCore.Qt.black)
else:
qp.setPen(QtCore.Qt.lightGray)
qp.setBrush(QtCore.Qt.transparent)
qp.drawPolygon(self.backwardArrow.translated(self.backwardRect.center()))
if self.currentIndex() < self.count() - 1:
qp.setPen(QtCore.Qt.darkGray)
qp.setBrush(QtCore.Qt.black)
else:
qp.setPen(QtCore.Qt.lightGray)
qp.setBrush(QtCore.Qt.transparent)
qp.drawPolygon(self.forwardArrow.translated(self.forwardRect.center()))
you have no logic in your ControlMainWindow class to switch between your widgets. (also i don't see any arrow widgets for switching) you'll need to add a listener to your QTbuttons in your main class like below to execute your logic:
yourQTbutton.itemClicked.connect(self.functioWithUIchangingLogic)
Related
I am trying to draw rectangle over Qgraphics scene. I found many examples but none of them are working for me. The rectangle is drawn on the area not covered by Qgraphics view widget in the window but when i try over the image it is not working. I don't know why. One observation is over the Qgraphicsview mouse release event is not getting executed. But i could not solve the issue. Any help will be helpful. Thanks in advance.
The code I am working in as is below.
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'zoom_win_qt.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
import numpy as np
from scipy.ndimage import zoom
import cv2
from matplotlib import pyplot as plt
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_zoom_win_qt(object):
def setupUi(self, zoom_win_qt):
zoom_win_qt.setObjectName(_fromUtf8("zoom_win_qt"))
zoom_win_qt.resize(800, 600)
self.centralwidget = QtGui.QWidget(zoom_win_qt)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.graphicsView = QtGui.QGraphicsView(self.centralwidget)
self.graphicsView.setGeometry(QtCore.QRect(80, 40, 611, 431))
self.graphicsView.setObjectName(_fromUtf8("graphicsView"))
grview = self.graphicsView
scene = QtGui.QGraphicsScene()
pixmap = QtGui.QPixmap('Koala.jpg')
pixmap = pixmap.scaledToHeight(420)
scene.addPixmap(pixmap)
grview.setScene(scene)
grview.show()
self.horizontalSlider = QtGui.QSlider(self.centralwidget)
self.horizontalSlider.setGeometry(QtCore.QRect(80, 500, 160, 19))
self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal)
self.horizontalSlider.setObjectName(_fromUtf8("horizontalSlider"))
self.progressBar = QtGui.QProgressBar(self.centralwidget)
self.progressBar.setGeometry(QtCore.QRect(590, 490, 118, 23))
self.progressBar.setProperty("value", 24)
self.progressBar.setObjectName(_fromUtf8("progressBar"))
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(380, 500, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.pushButton.clicked.connect(test_clipped_zoom)
zoom_win_qt.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(zoom_win_qt)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
zoom_win_qt.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(zoom_win_qt)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
zoom_win_qt.setStatusBar(self.statusbar)
self.retranslateUi(zoom_win_qt)
QtCore.QMetaObject.connectSlotsByName(zoom_win_qt)
def retranslateUi(self, zoom_win_qt):
zoom_win_qt.setWindowTitle(_translate("zoom_win_qt", "MainWindow", None))
self.pushButton.setText(_translate("zoom_win_qt", "PushButton", None))
class Myrect(QtGui.QMainWindow,Ui_zoom_win_qt):
def __init__(self, *args, **kwargs):
QtGui.QMainWindow.__init__(self, *args, **kwargs)
self.setupUi(self)
self.pos1 = [0,0]
self.pos2 = [0,0]
self.show()
def paintEvent(self, event):
width = self.pos2[0]-self.pos1[0]
height = self.pos2[1] - self.pos1[1]
qp = QtGui.QPainter()
qp.begin(self)
qp.drawRect(self.pos1[0], self.pos1[1], width, height)
qp.end()
def mousePressEvent(self, event):
self.pos1[0], self.pos1[1] = event.pos().x(), event.pos().y()
print("clicked")
def mouseReleaseEvent(self, event):
self.pos2[0], self.pos2[1] = event.pos().x(), event.pos().y()
print("released")
self.update()
def test_clipped_zoom():
zoom_win_qt.hide()
w.show()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
w = Myrect()
zoom_win_qt = QtGui.QMainWindow()
ui = Ui_zoom_win_qt()
ui.setupUi(zoom_win_qt)
zoom_win_qt.show()
sys.exit(app.exec_())
QGraphicsView is a widget to show a scene(QGraphicsScene), so the common thing is to add a rectangle to the scene (as if it were an actor), and not to paint. You are also painting in Myrect which is the widget where the other widgets are located so it is in the background, and the other widgets will cover the painting you do.
On the other hand it is not recommended to modify the class generated by Qt Designer, so I took the liberty to return it to its initial state
Returning to the starting point, to add a rectangle to the QGraphicsScene you must know the coordinates of those points in the coordinate system of the scene, so one way to do it is to use eventFilter(), this must filter the GraphicsSceneMousePress and GraphicsSceneMouseRelease events, these have the position and we can obtain it using the scenePos() method.
...
class Myrect(QtGui.QMainWindow,Ui_zoom_win_qt):
def __init__(self, *args, **kwargs):
QtGui.QMainWindow.__init__(self, *args, **kwargs)
self.setupUi(self)
self.pushButton.clicked.connect(test_clipped_zoom)
self.scene = QtGui.QGraphicsScene()
pixmap = QtGui.QPixmap('Koala.jpg').scaledToHeight(420)
self.scene.addPixmap(pixmap)
self.graphicsView.setScene(self.scene)
self.scene.installEventFilter(self)
self.start = QtCore.QPointF()
def eventFilter(self, obj, event):
if obj == self.scene:
if event.type() == QtCore.QEvent.GraphicsSceneMousePress:
self.start = event.scenePos()
elif event.type() == QtCore.QEvent.GraphicsSceneMouseRelease:
end = event.scenePos()
self.scene.addRect(QtCore.QRectF(self.start, end))
self.start = QtCore.QPointF()
return QtGui.QMainWindow.eventFilter(self, obj, event)
def test_clipped_zoom():
zoom_win_qt.hide()
w.show()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
w = Myrect()
w.show()
sys.exit(app.exec_())
Complete Code:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'zoom_win_qt.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_zoom_win_qt(object):
def setupUi(self, zoom_win_qt):
zoom_win_qt.setObjectName(_fromUtf8("zoom_win_qt"))
zoom_win_qt.resize(800, 600)
self.centralwidget = QtGui.QWidget(zoom_win_qt)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.graphicsView = QtGui.QGraphicsView(self.centralwidget)
self.graphicsView.setGeometry(QtCore.QRect(80, 40, 611, 431))
self.graphicsView.setObjectName(_fromUtf8("graphicsView"))
self.horizontalSlider = QtGui.QSlider(self.centralwidget)
self.horizontalSlider.setGeometry(QtCore.QRect(80, 500, 160, 19))
self.horizontalSlider.setOrientation(QtCore.Qt.Horizontal)
self.horizontalSlider.setObjectName(_fromUtf8("horizontalSlider"))
self.progressBar = QtGui.QProgressBar(self.centralwidget)
self.progressBar.setGeometry(QtCore.QRect(590, 490, 118, 23))
self.progressBar.setProperty("value", 24)
self.progressBar.setObjectName(_fromUtf8("progressBar"))
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(380, 500, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
zoom_win_qt.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(zoom_win_qt)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
zoom_win_qt.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(zoom_win_qt)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
zoom_win_qt.setStatusBar(self.statusbar)
self.retranslateUi(zoom_win_qt)
QtCore.QMetaObject.connectSlotsByName(zoom_win_qt)
def retranslateUi(self, zoom_win_qt):
zoom_win_qt.setWindowTitle(_translate("zoom_win_qt", "MainWindow", None))
self.pushButton.setText(_translate("zoom_win_qt", "PushButton", None))
class Myrect(QtGui.QMainWindow,Ui_zoom_win_qt):
def __init__(self, *args, **kwargs):
QtGui.QMainWindow.__init__(self, *args, **kwargs)
self.setupUi(self)
self.pushButton.clicked.connect(test_clipped_zoom)
self.scene = QtGui.QGraphicsScene()
pixmap = QtGui.QPixmap('Koala.jpg').scaledToHeight(420)
self.scene.addPixmap(pixmap)
self.graphicsView.setScene(self.scene)
self.scene.installEventFilter(self)
self.start = QtCore.QPointF()
def eventFilter(self, obj, event):
if obj == self.scene:
if event.type() == QtCore.QEvent.GraphicsSceneMousePress:
self.start = event.scenePos()
elif event.type() == QtCore.QEvent.GraphicsSceneMouseRelease:
end = event.scenePos()
self.scene.addRect(QtCore.QRectF(self.start, end))
self.start = QtCore.QPointF()
return QtGui.QMainWindow.eventFilter(self, obj, event)
def test_clipped_zoom():
zoom_win_qt.hide()
w.show()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
w = Myrect()
w.show()
sys.exit(app.exec_())
This app is a basic Drag'n'Drop program and should handle dropped .html files.
So far I have written this code:
main.py
from PyQt4 import QtGui
import sys
import design, os
class MyTextEdit(QtGui.QTextEdit):
def __init__(self, parent):
super(MyTextEdit, self).__init__(parent)
self.setAcceptDrops(True)
self.list_of_dropped_files = []
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
event.accept()
def dropEvent(self, event):
self.clear()
self.list_of_dropped_files = event.mimeData().urls()
for single_file in self.list_of_dropped_files:
self.append(single_file.toLocalFile())
class DialogInit(QtGui.QDialog, design.Ui_Dialog):
def __init__(self):
super(self.__class__, self).__init__()
self.setupUi(self)
self.buttonBox.accepted.connect(self.accept) # handle the ok button click
self.textEditHandler = MyTextEdit(self.textEdit)
def accept(self):
print self.textEditHandler.list_of_dropped_files
def main():
app = QtGui.QApplication(sys.argv)
form = DialogInit()
form.show()
app.exec_()
if __name__ == '__main__':
main()
and I created also a design.py code using the QtDesigner that looks like as follows:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(409, 80)
self.verticalLayoutWidget = QtGui.QWidget(Dialog)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 401, 71))
self.verticalLayoutWidget.setObjectName(_fromUtf8("verticalLayoutWidget"))
self.verticalLayout = QtGui.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.label = QtGui.QLabel(self.verticalLayoutWidget)
font = QtGui.QFont()
font.setPointSize(12)
self.label.setFont(font)
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout.addWidget(self.label)
self.textEdit = QtGui.QTextEdit(self.verticalLayoutWidget)
self.textEdit.setAcceptDrops(True)
self.textEdit.setObjectName(_fromUtf8("textEdit"))
self.horizontalLayout.addWidget(self.textEdit)
self.verticalLayout.addLayout(self.horizontalLayout)
self.buttonBox = QtGui.QDialogButtonBox(self.verticalLayoutWidget)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
self.verticalLayout.addWidget(self.buttonBox)
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), Dialog.reject)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), Dialog.accept)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
self.label.setText(_translate("Dialog", "Drop .html file(s):", None))
However, after the Ok button from the button box has been pressed, the event and therefore the function accept(), is fired twice.
Furthermore I found that after dropping several files into the QTextEdit, the widget doesn't change its height or at least a scroll pane is added automatically.
Any ideas how to fix the both issues?
I think also that my code is pretty messed up, it works, but it is not really well programmed.
Can someone please give an advice how to refactor the code? What could I have been better?
Thanks!
I've found myself a solution for closing the QDialog issue after the ok button has been clicked. I had to remove the accept() slot in the design.py.
However, I still can't see a scrollbar added when several files have been droppped.
I have two buttons (wgtbtnA & wgtbtnB) placed on two different pages (page1 and page2, respectively) inside a parent object (objectName: stackedWidget). My dilemma is this: when I run the code, the arrows don't display in PyQt. Why? How do I alternate from page1 to page2 and vice-versa?
Here is an image of runtime, which conveys what I am asking for:
Qt Designer:
I'd like to keep those small back arrows.
Below is my code:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'stackedWidget.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
import sys
import os
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(512, 304)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.stackedWidget = QtGui.QStackedWidget(self.centralwidget)
self.stackedWidget.setGeometry(QtCore.QRect(150, 60, 161, 121))
self.stackedWidget.setObjectName(_fromUtf8("stackedWidget"))
self.page = QtGui.QWidget()
self.page.setObjectName(_fromUtf8("page"))
self.wgtMainWindow = QtGui.QPushButton(self.page)
self.wgtMainWindow.setGeometry(QtCore.QRect(50, 50, 75, 23))
self.wgtMainWindow.setObjectName(_fromUtf8("wgtMainWindow"))
self.stackedWidget.addWidget(self.page)
self.page_2 = QtGui.QWidget()
self.page_2.setObjectName(_fromUtf8("page_2"))
self.wgtbtnB = QtGui.QPushButton(self.page_2)
self.wgtbtnB.setGeometry(QtCore.QRect(50, 50, 75, 23))
self.wgtbtnB.setObjectName(_fromUtf8("wgtbtnB"))
self.stackedWidget.addWidget(self.page_2)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 512, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.stackedWidget.setCurrentIndex(1)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.wgtMainWindow.setText(_translate("MainWindow", "Widget A", None))
self.wgtbtnB.setText(_translate("MainWindow", "Widget B", None))
class ControlMainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(ControlMainWindow, self).__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
mySW = ControlMainWindow()
mySW.show()
sys.exit(app.exec_())
You could use the buttons to change the page: {your QPushButton}.clicked.connect(lambda: {your QStackedWidget}.setCurrentIndex({another page}))
By Example:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'stackedWidget.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
import sys
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(512, 304)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.stackedWidget = QtGui.QStackedWidget(self.centralwidget)
self.stackedWidget.setGeometry(QtCore.QRect(150, 60, 161, 121))
self.stackedWidget.setObjectName(_fromUtf8("stackedWidget"))
self.page = QtGui.QWidget()
self.page.setObjectName(_fromUtf8("page"))
self.wgtMainWindow = QtGui.QPushButton(self.page)
self.wgtMainWindow.setGeometry(QtCore.QRect(50, 50, 75, 23))
self.wgtMainWindow.setObjectName(_fromUtf8("wgtMainWindow"))
self.stackedWidget.addWidget(self.page)
self.page_2 = QtGui.QWidget()
self.page_2.setObjectName(_fromUtf8("page_2"))
self.wgtbtnB = QtGui.QPushButton(self.page_2)
self.wgtbtnB.setGeometry(QtCore.QRect(50, 50, 75, 23))
self.wgtbtnB.setObjectName(_fromUtf8("wgtbtnB"))
self.stackedWidget.addWidget(self.page_2)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 512, 21))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.stackedWidget.setCurrentIndex(1)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.wgtMainWindow.setText(_translate("MainWindow", "Widget A", None))
self.wgtbtnB.setText(_translate("MainWindow", "Widget B", None))
class ControlMainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(ControlMainWindow, self).__init__(parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.wgtbtnB.clicked.connect(lambda : self.ui.stackedWidget.setCurrentIndex(0))
self.ui.wgtMainWindow.clicked.connect(lambda : self.ui.stackedWidget.setCurrentIndex(1))
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
mySW = ControlMainWindow()
mySW.show()
sys.exit(app.exec_())
Start app:
after clicked button:
after clicked another button:
the two arrows you see in the designer ( in your message below) don't carry over to your application, its a function in the designer so you can switch between them easily
To implement your arrows from one screen to the next you just need to propagate those arrows making sure that they appear in each view -- now this can easily be done via code cannot say how difficult it might be in the designer. Here is a example that does something like what you might be wanting.
from sys import exit as sysExit
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Win1Disply(QFrame):
def __init__(self, parent):
QFrame.__init__(self)
self.setFrameShape(QFrame.StyledPanel)
self.setLineWidth(0.2)
# -------
self.Cntnr = QVBoxLayout()
self.Cntnr.addWidget(QTextEdit('This is Window 1 with whatever contents you want'))
self.Win1Btn = QPushButton('>>')
self.Win1Btn.clicked.connect(parent.RightArrow)
self.Cntnr.addWidget(self.Win1Btn)
self.Cntnr.addStretch(1)
# -------
self.setLayout(self.Cntnr)
class Win2Disply(QFrame):
def __init__(self, parent):
QFrame.__init__(self)
self.setFrameShape(QFrame.StyledPanel)
self.setLineWidth(0.2)
# -------
self.Cntnr = QVBoxLayout()
self.Cntnr.addWidget(QTextEdit('This is Window 2 with whatever contents you want'))
self.Win1Btn = QPushButton('>>')
self.Win1Btn.clicked.connect(parent.RightArrow)
self.Cntnr.addWidget(self.Win1Btn)
self.Cntnr.addStretch(1)
# -------
self.setLayout(self.Cntnr)
class OptionButtons(QToolButton):
# Class OptionButtons ("Text", Connector) inherits from QToolButton
def __init__(self, Text, Connector):
QToolButton.__init__(self)
self.setText(Text)
self.setStyleSheet("font: bold;color: blue;height: 55px;width: 55px;")
self.setIconSize(QSize(32,32))
self.clicked.connect(Connector)
############################## Settings Class ##############################
class OptionSettings(QDialog):
def __init__(self, parent):
QDialog.__init__(self, parent)
line = QFrame()
line.setFrameShape(QFrame.HLine)
line.setFrameShadow(QFrame.Sunken)
self.btnWin1 = OptionButtons('Win One', self.ShowWindow1)
self.btnWin2 = OptionButtons('Win Two', self.ShowWindow2)
# Vertical Box for Buttons *************************************
self.UpLeft = QVBoxLayout()
self.UpLeft.addWidget(self.btnWin1)
self.UpLeft.addWidget(self.btnWin2)
self.UpLeft.addStretch(1)
# Display Area on Right
# Widget Flip Display ******************************************
self.UpRite = QHBoxLayout()
self.Contents = QStackedWidget()
self.Contents.addWidget(QTextEdit('Nothing Selected'))
self.Contents.addWidget(Win1Disply(self))
self.Contents.addWidget(Win2Disply(self))
self.Contents.addWidget(QTextEdit('Settings Saved'))
self.Contents.setCurrentIndex(0)
self.UpRite.addWidget(self.Contents)
# Button and Display Area on Top
self.Upper = QHBoxLayout()
self.Upper.addLayout(self.UpLeft)
self.Upper.addLayout(self.UpRite)
# Save and Cancel Area on Bottom
self.btnSave = QPushButton("Save")
self.btnSave.clicked.connect(self.SaveSettings)
self.btnCncl = QPushButton("Cancel")
self.btnCncl.clicked.connect(self.close)
self.Lower = QHBoxLayout()
self.Lower.addStretch(1)
self.Lower.addWidget(self.btnSave)
self.Lower.addWidget(self.btnCncl)
# Entire Options Window Layout
self.OuterBox = QVBoxLayout()
self.OuterBox.addLayout(self.Upper)
self.OuterBox.addLayout(self.Lower)
self.setLayout(self.OuterBox)
self.setWindowTitle('Settings')
#Geometry(Left, Top, Width, Hight)
self.setGeometry(250, 250, 550, 450)
self.setModal(True)
self.exec()
def ShowWindow1(self):
self.Contents.setCurrentIndex(1)
def ShowWindow2(self):
self.Contents.setCurrentIndex(2)
def SaveSettings(self):
self.Contents.setCurrentIndex(3)
def RightArrow(self):
if self.Contents.currentIndex() == 1:
self.Contents.setCurrentIndex(2)
else:
self.Contents.setCurrentIndex(1)
class CenterPanel(QWidget):
def __init__(self, MainWin):
QWidget.__init__(self)
CntrPane = QTextEdit('Center Panel is Placed Here')
hbox = QHBoxLayout(self)
hbox.addWidget(CntrPane)
self.setLayout(hbox)
class MenuToolBar(QDockWidget):
def __init__(self, MainWin):
QDockWidget.__init__(self)
self.MainWin = MainWin
self.MainMenu = MainWin.menuBar()
self.WndowMenu = self.MainMenu.addMenu('Windows')
self.OptnAct = QAction('Options', self)
self.OptnAct.setStatusTip('Open the Options Window')
self.OptnAct.triggered.connect(MainWin.ShowOptions)
self.WndowMenu.addAction(self.OptnAct)
self.InitToolBar(MainWin)
def InitToolBar(self, MainWin):
self.mainToolBar = MainWin.addToolBar("Quick Access")
self.mainToolBar.addAction(self.OptnAct)
class UI_MainWindow(QMainWindow):
def __init__(self):
super(UI_MainWindow, self).__init__()
self.setWindowTitle('Main Window')
# Left, Top, Width, Height
self.setGeometry(200, 200, 550, 550)
self.CenterPane = CenterPanel(self)
self.setCentralWidget(self.CenterPane)
self.MenuToolBar = MenuToolBar(self)
def ShowOptions(self):
self.Options = OptionSettings(self)
if __name__ == '__main__':
MainApp = QApplication([])
MainGui = UI_MainWindow()
MainGui.show()
sysExit(MainApp.exec_())
If you really need arrows in your stacked widget, another solution is to implement your own "Promoted Widget": it allows you to create your design with custom widgets, that might extend the basic widgets provided by Qt. You won't be able to interact with your own implementation in Designer, but you'll get the result once you run your program.
This is the procedure: create your own subclass of the widget you want to extend, define your custom methods or override existing ones (remember that some private methods require a specific return value type, check the documentation).
It's usually better to save the subclass(es) you created in a separate files.
Then, in Designer add the widget you need (in this case, StackedWidget), right click on it and select "Promote to..."; in the dialog that will be shown, type the subclass name you created in the "Promoted class name" field (in the example below, it will be "StackedWidgetWithArrowButtons") and the file that contains it in the "header file" field: it will be treated as a python import, so do not add the trailing ".py" and remember that if you saved it in a subdirectory you'll need the full "module" path, for example "mysubclasses.customstackwidget", if the file is "customstackwidget" in the "mysubclasses" directory.
Save the ui, compile it and run the program.
class StackedWidgetWithArrowButtons(QtWidgets.QStackedWidget):
def __init__(self, *args, **kwargs):
QtWidgets.QStackedWidget.__init__(self, *args, **kwargs)
self.backwardButton = QtWidgets.QToolButton(self)
self.backwardButton.setIcon(self.style().standardIcon(QtWidgets.QStyle.SP_ArrowLeft))
self.backwardButton.setMaximumSize(24, 24)
self.backwardButton.setFocusPolicy(QtCore.Qt.NoFocus)
self.forwardButton = QtWidgets.QToolButton(self)
self.forwardButton.setIcon(self.style().standardIcon(QtWidgets.QStyle.SP_ArrowRight))
self.forwardButton.setMaximumSize(24, 24)
self.forwardButton.setFocusPolicy(QtCore.Qt.NoFocus)
self.currentChanged.connect(self.checkSwitchButtons)
def checkSwitchButtons(self):
self.forwardButton.setEnabled(self.currentIndex() < self.count() - 1)
self.backwardButton.setEnabled(self.currentIndex() > 0)
def addWidget(self, widget):
# this is a private method of QStackedWidget that is called when
# the ui is being built by the program, we just implement it
# to ensure that the buttons are correctly enabled;
# the index *has* to be returned
index = QtWidgets.QStackedWidget.addWidget(self, widget)
self.checkSwitchButtons()
return index
def removeWidget(self, widget):
# not necessary, but in case you want to remove widgets in the
# future, it will check buttons again
index = QtWidgets.QStackedWidget.removeWidget(self, widget)
self.checkSwitchButtons()
return index
def mousePressEvent(self, event):
# due to the way QStackedWidget is implemented, children widgets
# that are not in its layout might not receive mouse events,
# but we just need to track clicks so this is enough
if event.button() == QtCore.Qt.LeftButton:
if event.pos() in self.backwardButton.geometry():
self.setCurrentIndex(self.currentIndex() - 1)
elif event.pos() in self.forwardButton.geometry():
self.setCurrentIndex(self.currentIndex() + 1)
def resizeEvent(self, event):
# the base class resizeEvent *has* to be called, otherwise
# you could encounter problems with children widgets
QtWidgets.QStackedWidget.resizeEvent(self, event)
# now ensure that the buttons are always placed on the top
# right corner; this positioning is completely manual and you
# have to take button sizes in consideration to avoid
# overlapping buttons; obviously you can place them wherever
# you want.
self.forwardButton.move(self.rect().right() - self.forwardButton.width(), 0)
self.backwardButton.move(self.forwardButton.x() - self.backwardButton.width(), 0)
If you don't want buttons (or you don't like the way they appear) you could implement your own paintEvent. In this case I created small triangles using QPolygons.
class StackedWidgetWithTriangles(QtWidgets.QStackedWidget):
def __init__(self, *args, **kwargs):
QtWidgets.QStackedWidget.__init__(self, *args, **kwargs)
self.backwardRect = QtCore.QRect(0, 0, 16, 16)
self.forwardRect = QtCore.QRect(0, 0, 16, 16)
self.forwardArrow = QtGui.QPolygon([QtCore.QPoint(-6, -6), QtCore.QPoint(6, 0), QtCore.QPoint(-6, 6)])
self.backwardArrow = QtGui.QPolygon([QtCore.QPoint(6, -6), QtCore.QPoint(-6, 0), QtCore.QPoint(6, 6)])
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
if event.pos() in self.backwardRect:
self.setCurrentIndex(self.currentIndex() - 1)
elif event.pos() in self.forwardRect:
self.setCurrentIndex(self.currentIndex() + 1)
def resizeEvent(self, event):
QtWidgets.QStackedWidget.resizeEvent(self, event)
self.forwardRect.moveLeft(self.rect().right() - self.forwardRect.width())
self.backwardRect.moveLeft(self.forwardRect.x() - self.forwardRect.width())
def paintEvent(self, event):
qp = QtGui.QPainter(self)
qp.setRenderHints(qp.Antialiasing)
# set colors according to the possibility of going back or forward,
# showing a "disabled" arrow whenever it's not possible
if self.currentIndex() > 0:
qp.setPen(QtCore.Qt.darkGray)
qp.setBrush(QtCore.Qt.black)
else:
qp.setPen(QtCore.Qt.lightGray)
qp.setBrush(QtCore.Qt.transparent)
qp.drawPolygon(self.backwardArrow.translated(self.backwardRect.center()))
if self.currentIndex() < self.count() - 1:
qp.setPen(QtCore.Qt.darkGray)
qp.setBrush(QtCore.Qt.black)
else:
qp.setPen(QtCore.Qt.lightGray)
qp.setBrush(QtCore.Qt.transparent)
qp.drawPolygon(self.forwardArrow.translated(self.forwardRect.center()))
you have no logic in your ControlMainWindow class to switch between your widgets. (also i don't see any arrow widgets for switching) you'll need to add a listener to your QTbuttons in your main class like below to execute your logic:
yourQTbutton.itemClicked.connect(self.functioWithUIchangingLogic)
I need your help with my app. I undecorated python gui and now i need to create clicable label.
run.py
from PyQt4 import QtCore, QtGui
import sys
import untitled
class ExampleApp(QtGui.QMainWindow, untitled.Ui_MainWindow):
def __init__(self):
super(self.__class__, self).__init__()
self.setupUi(self)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
def main():
app = QtGui.QApplication(sys.argv)
form = ExampleApp()
form.show()
app.exec_()
if __name__ == '__main__':
main()
def closeapp():
sys.exit(0);
untitled.py:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(800, 600)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(40, 110, 85, 30))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.label = QtGui.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(220, 100, 58, 14))
self.label.setObjectName(_fromUtf8("label"))
self.label_2 = QtGui.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(220, 140, 58, 14))
self.label_2.setObjectName(_fromUtf8("label_2"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 26))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.pushButton.setText(_translate("MainWindow", "open", None))
self.label.setText(_translate("MainWindow", "close", None))
self.label_2.setText(_translate("MainWindow", "view", None))
Now I need to add action to label and label_2. How to make the label to perform closeapp()?
Add a function to Ui_MainWindow class (untitled.py)
def click(self,eve):
print "clicked"
Then add attribute to label object
self.label.mousePressEvent = self.click
another option is just modify run.py file like following
class ExampleApp(QtGui.QMainWindow, untitled.Ui_MainWindow):
def click(self,eve):
print "clicked"
def __init__(self):
super(self.__class__, self).__init__()
self.setupUi(self)
self.label.mousePressEvent = self.click
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
QLabel inherits QWidget. QWidget` has an event handler mousePressEvent
so as E-ebola virus mentioned
add
self.label.mousePressEvent = self.click
and define
def click(self,event):
#do something
or
subclass QLabel
class customLabel(QLabel):
def __init__(self):
QLabel.__init__(self)
def self.mousePressEvent(self,event):
self.emit(SIGNAL("closeapp"))
emit a SIGNAL when label is pressed, i would implement it as
self.label = customLabel()
self.connect(self.label,SIGNAL('closeapp'),self.close)
I'm trying to write a script which will display a busy indication
while performing the task. And when the task is over, the progress bar
will fill to the end showing that 100% task has been completed.
I just want the progress bar to show a task is going on.But when I start
the task, busy indication stops.It seems to me that the indication and
the task can not continue together. Please help me. Here's mycode:
from PyQt4 import QtCore, QtGui
from time import sleep
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(344, 159)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.pb = QtGui.QProgressBar(self.centralwidget)
self.pb.setGeometry(QtCore.QRect(20, 20, 301, 31))
self.pb.setProperty("value", 0)
self.pb.setObjectName(_fromUtf8("pb"))
self.btn = QtGui.QPushButton(self.centralwidget)
self.btn.setGeometry(QtCore.QRect(20, 70, 98, 27))
self.btn.setObjectName(_fromUtf8("btn"))
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 344, 25))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QObject.connect(self.btn, QtCore.SIGNAL(_fromUtf8("clicked()")), self.action)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def action(self):
self.pb.setRange(0, 0)
sleep(3) # Here I want to run a command.For example: os.system('copy something')
self.pb.setRange(0, 100)
self.pb.setValue(100)
QtGui.qApp.processEvents()
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.btn.setText(_translate("MainWindow", "Start", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
First, it's a bad idea to directly edit the code created with QtDesigner. You may have seen the line # WARNING! All changes made in this file will be lost! at the top of the document. For such a simple widget, you're better off with manual coding.
Secondly, take a closer look at what the action slot actually does.
def action(self):
self.pb.setRange(0, 0) # Un
sleep(3) # <-- Your slot blocks HERE
self.pb.setRange(0, 100)
self.pb.setValue(100)
QtGui.qApp.processEvents()
There is no reason for your progressBar to update its value while your slot is blocked in sleep. When action is called, the slot thread sleeps for 3 sec then sets the progress bar to a full 100.
You can't expect the progressBar to magically update itself while your task is running. If you have no idea how long it will take and you can't subdivise it in steps, you should consider using a pulsed ProgressBar instead (see example 1 below). If you can easily get the progression of your task (say copying n files), you should update the value of your progressBar accordingly.
Either way, you should use QThread to get a non-blocking behaviour, and signals to communicate between your thread(s) and your main application.
The main application starts the QThread implementing the long-running task.
The QThread notifies the task progression (if available) or completion to the main application
Example 1 - Pulse ProgressBar:
If minimum and maximum are both set to 0, the progress bar will show a busy indicator instead of a percentage of steps.
class MyCustomWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(MyCustomWidget, self).__init__(parent)
layout = QtGui.QVBoxLayout(self)
# Create a progress bar and a button and add them to the main layout
self.progressBar = QtGui.QProgressBar(self)
self.progressBar.setRange(0,1)
layout.addWidget(self.progressBar)
button = QtGui.QPushButton("Start", self)
layout.addWidget(button)
button.clicked.connect(self.onStart)
self.myLongTask = TaskThread()
self.myLongTask.taskFinished.connect(self.onFinished)
def onStart(self):
self.progressBar.setRange(0,0)
self.myLongTask.start()
def onFinished(self):
# Stop the pulsation
self.progressBar.setRange(0,1)
class TaskThread(QtCore.QThread):
taskFinished = QtCore.pyqtSignal()
def run(self):
time.sleep(3)
self.taskFinished.emit()
Example 2 - Classic ProgressBar:
class MyCustomWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(MyCustomWidget, self).__init__(parent)
layout = QtGui.QVBoxLayout(self)
self.progressBar = QtGui.QProgressBar(self)
self.progressBar.setRange(0,100)
button = QtGui.QPushButton("Start", self)
layout.addWidget(self.progressBar)
layout.addWidget(button)
button.clicked.connect(self.onStart)
self.myLongTask = TaskThread()
self.myLongTask.notifyProgress.connect(self.onProgress)
def onStart(self):
self.myLongTask.start()
def onProgress(self, i):
self.progressBar.setValue(i)
class TaskThread(QtCore.QThread):
notifyProgress = QtCore.pyqtSignal(int)
def run(self):
for i in range(101):
self.notifyProgress.emit(i)
time.sleep(0.1)
A bit late, but I've written detailed documentation on this very issue since a lot of people seem to face this problem.
Introduction to Progress Bars
Finally I got what I wanted, though little bit editing needed . I just added this line
to onFinished():
self.progressBar.setValue(1)
to confirm 100% task completion.
Here's the code:
from PyQt4 import QtCore, QtGui
from time import sleep
import sys, os
class MyCustomWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(MyCustomWidget, self).__init__(parent)
layout = QtGui.QVBoxLayout(self)
# Create a progress bar and a button and add them to the main layout
self.progressBar = QtGui.QProgressBar(self)
self.progressBar.setRange(0,1)
layout.addWidget(self.progressBar)
button = QtGui.QPushButton("Start", self)
layout.addWidget(button)
button.clicked.connect(self.onStart)
self.myLongTask = TaskThread()
self.myLongTask.taskFinished.connect(self.onFinished)
def onStart(self):
self.progressBar.setRange(0,0)
self.myLongTask.start()
def onFinished(self):
# Stop the pulsation
self.progressBar.setRange(0,1)
self.progressBar.setValue(1)
class TaskThread(QtCore.QThread):
taskFinished = QtCore.pyqtSignal()
def run(self):
os.system('sudo apt-get install leafpad')
self.taskFinished.emit()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MyCustomWidget()
window.resize(640, 480)
window.show()
sys.exit(app.exec_())
apply this:
progressbar.setMinimum(0)
progressbar.setMaximum(0)
progressbar.setValue(0)
This setting will have a busy appearance, You do not need to add it to any function, it can be in the class constructor if you want