I have QStackedWidget in ApplicationWindow class and buttons which are going to point to different QWidgets in MenuWindow. I need a help with writing a function which would change the CurrentWidget according to button clicked - e.g. login_button would change the CurrentWidget to LoginWindow.
When trying to do it myself I ran into recursion problems as I have just started with learning Python.
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
class ApplicationWindow(QWidget):
def __init__(self):
super(ApplicationWindow, self).__init__()
# stack = Controller()
self.menu = MenuWindow()
self.login = LoginWindow()
self.setGeometry(0, 0, 800, 600)
self.setWindowTitle('Finance tracker')
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.green)
self.setPalette(p)
self.stack = QStackedWidget()
self.stack.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
self.stack.addWidget(self.menu)
self.stack.addWidget(self.login)
self.stack.setCurrentWidget(self.menu)
layout = QVBoxLayout()
layout.addWidget(self.stack)
layout.setAlignment(Qt.AlignCenter)
self.setLayout(layout)
class MenuWindow(QWidget):
def __init__(self):
super(MenuWindow, self).__init__()
self.setGeometry(0, 0, 250, 200)
box = QVBoxLayout()
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.red)
self.setPalette(p)
label = QLabel('Welcome to finance tracker')
label.setStyleSheet('font: 24pt')
box.addWidget(label, alignment=Qt.AlignCenter)
login_button = QPushButton('Login')
login_button.clicked.connect(qApp.exit)
new_button = QPushButton('Create a new account')
new_button.clicked.connect(qApp.exit)
exit_button = QPushButton('Exit')
exit_button.clicked.connect(qApp.exit)
for button in [login_button, new_button, exit_button]:
button.setStyleSheet('font: 14pt')
button.setFixedSize(200, 50)
box.addWidget(button, alignment=Qt.AlignCenter)
self.setLayout(box)
self.show()
class LoginWindow(QWidget):
def __init__(self):
super(LoginWindow, self).__init__()
self.setGeometry(0, 0, 10, 250)
self.setAutoFillBackground(True)
p = self.palette()
p.setColor(self.backgroundRole(), Qt.blue)
self.setPalette(p)
label = QLabel('Welcome to finance tracker')
box = QVBoxLayout()
box.addWidget(label)
self.setLayout(box)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = ApplicationWindow()
window.show()
sys.exit(app.exec())
Since you are using QPushButtons to switch pages I would add them to a QButtonGroup. This way you can connect the QButtonGroup.buttonClicked[int] signal to QStackedWidget.setCurrentIndex. Keep a pointer to the QButtonGroup in your MenuWindow.
class MenuWindow(QWidget):
def __init__(self):
...
login_button = QPushButton('Login')
new_button = QPushButton('Create a new account')
exit_button = QPushButton('Exit')
exit_button.clicked.connect(qApp.exit)
self.btn_group = QButtonGroup()
for i, button in enumerate([login_button, new_button, exit_button]):
button.setStyleSheet('font: 14pt')
button.setFixedSize(200, 50)
box.addWidget(button, alignment=Qt.AlignCenter)
self.btn_group.addButton(button)
self.btn_group.setId(button, i + 1)
...
And now you can connect the signal and slot in your ApplicationWindow.
class ApplicationWindow(QWidget):
def __init__(self):
...
self.menu.btn_group.buttonClicked[int].connect(self.stack.setCurrentIndex)
Related
i am new in PyQt but i have a problem i can't solve. I am trying to get text from second window and set it to field, so when i close second window i can print it form first main window, but my "AnotherWindow" button won't fire event and i really don't know why? Here is code. Can anyone guide me?
Thanks
class AnotherWindow(QMainWindow):
def __init__(self):
super().__init__()
self.resize(1200, 600)
self.text = "basetext"
self.layoutf = QFormLayout()
self.buttonf = QPushButton("get text")
self.buttonf.clicked.connect(lambda: self.getText)
self.line = QLineEdit()
self.layoutf.addRow(self.buttonf,self.line)
self.widgetf = QWidget()
self.widgetf.setLayout(self.layoutf)
self.setCentralWidget(self.widgetf)
def getText(self):
print(self.line.text)
self.text = self.line.text
self.close()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.w = None # No external window yet.
self.mainLayout = QGridLayout()
self.button = QPushButton("Push for Window")
self.button.clicked.connect(self.show_new_window)
self.button1 = QPushButton("Push ")
self.button1.clicked.connect(self.printFromSecondWindow)
self.mainLayout.addWidget(self.button,0,0)
self.mainLayout.addWidget(self.button1, 0, 1)
self.widget = QWidget()
self.widget.setLayout(self.mainLayout)
self.setCentralWidget(self.widget)
def show_new_window(self):
if self.w is None:
self.w = AnotherWindow()
self.w.show()
else:
self.w.close() # Close window.
self.w = None # Discard reference.
def printFromSecondWindow(self):
print(self.w.text)
app = QApplication(sys.argv)
w = MainWindow()
w.show()
app.exec_()
The problem is with self.buttonf.clicked.connect(...). This call attaches a function to the "clicked" action on the button. The function is called without parameters and the return is simply discarded. In your case, lambda: self.get_text is a function that does nothing but return the address of the self.get_text method. Since get_text doesn't need any additional parameters, you can bind it directly to this slot.
self.buttonf.clicked.connect(self.get_text)
You also have a bug later on where you need to call the text method. With these two changes, the working program is
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.Qt import *
class AnotherWindow(QMainWindow):
def __init__(self):
super().__init__()
self.resize(1200, 600)
self.text = "basetext"
self.layoutf = QFormLayout()
self.buttonf = QPushButton("get text")
self.buttonf.clicked.connect(self.getText)
self.line = QLineEdit()
self.layoutf.addRow(self.buttonf,self.line)
self.widgetf = QWidget()
self.widgetf.setLayout(self.layoutf)
self.setCentralWidget(self.widgetf)
def getText(self):
print("the info", self.line.text())
self.text = self.line.text()
self.close()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.w = None # No external window yet.
self.mainLayout = QGridLayout()
self.button = QPushButton("Push for Window")
self.button.clicked.connect(self.show_new_window)
self.button1 = QPushButton("Push ")
self.button1.clicked.connect(self.printFromSecondWindow)
self.mainLayout.addWidget(self.button,0,0)
self.mainLayout.addWidget(self.button1, 0, 1)
self.widget = QWidget()
self.widget.setLayout(self.mainLayout)
self.setCentralWidget(self.widget)
def show_new_window(self):
if self.w is None:
self.w = AnotherWindow()
self.w.show()
else:
self.w.close() # Close window.
self.w = None # Discard reference.
def printFromSecondWindow(self):
print(self.w.text)
app = QApplication(sys.argv)
w = MainWindow()
w.show()
app.exec_()
Instantiate the second window once in the main window constructor. self.w = AnotherWindow (self)
When creating an instance of the second window, self.w = AnotherWindow (self) - self is passed as a parent, so that when the main window is closed, the second window also closes.
To get text from a QLineEdit widget - apply QString text() const, more https://doc.qt.io/qt-5/qlineedit.html#text-prop
You did not show the method printFromSecondWindow in which, as I understand it, you wanted to show what you intended.
Try it:
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.Qt import *
class AnotherWindow(QMainWindow):
def __init__(self, parent=None):
super(AnotherWindow, self).__init__(parent)
self.widgetf = QWidget()
self.setCentralWidget(self.widgetf)
# self.resize(1200, 600)
self.text = "basetext"
self.layoutf = QFormLayout(self.widgetf)
self.buttonf = QPushButton("get text")
# self.buttonf.clicked.connect(lambda: self.getText) # ??? lambda
self.buttonf.clicked.connect(self.getText)
self.line = QLineEdit()
self.layoutf.addRow(self.buttonf,self.line)
def getText(self):
print(self.line.text()) # ! .text()
self.text = self.line.text() # ! .text()
self.close()
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.widget = QWidget()
self.setCentralWidget(self.widget)
# ? self.w = None # No external window yet.
self.button = QPushButton("Push for Window")
self.button.clicked.connect(self.show_new_window)
self.button1 = QPushButton("Push ")
self.button1.clicked.connect(self.printFromSecondWindow)
self.mainLayout = QGridLayout(self.widget)
self.mainLayout.addWidget(self.button, 0, 0)
self.mainLayout.addWidget(self.button1, 0, 1)
self.w = AnotherWindow(self) # +++
def show_new_window(self):
# if self.w is None:
# self.w = AnotherWindow()
self.w.show() # !
# else:
# self.w.close() # Close window.
# self.w = None # Discard reference.
def printFromSecondWindow(self): # +++
print(self.w.text)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
import sys
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import QApplication,QDialog,QPushButton,QVBoxLayout,QWidget
class Main(QDialog):
def __init__(self):
super(Main, self).__init__()
self.ui()
# Group Of Drage Event
def mousePressEvent(self,event):
self.offset = event.pos()
def mouseMoveEvent(self, e):
x = e.globalX()
y = e.globalY()
x_w = self.offset.x()
y_w = self.offset.y()
self.move(x - x_w, y - y_w)
def ui(self):
# TitleBar
self.setWindowFlags(Qt.FramelessWindowHint)
# Window Size
self.setGeometry(600,300,400,500)
# Window Background Color
self.BackGroundColor = QPalette()
self.BackGroundColor.setColor(QPalette.Background, QColor(255,255,255))
self.setPalette(self.BackGroundColor)
# NavBar Button
self.btn = QPushButton('Test',self)
self.btn1 = QPushButton("Test1",self)
# NavBar Layout
self.layout = QVBoxLayout(self)
self.layout.addWidget(self.btn)
self.layout.addWidget(self.btn1)
self.layout.set
self.setLayout(self.layout)
# Close img
self.closeBtn = QPushButton(self)
self.closeBtn.setGeometry(368,0,32,32)
self.closeBtn.setFlat(True)
self.closeBtn.setStyleSheet('QPushButton{background-color: rgba(0,0,0,0.0)}')
self.closeBtn.setIcon(QIcon('img/close.png'))
self.closeBtn.setIconSize(QSize(10,10))
self.closeBtn.clicked.connect(QCoreApplication.instance().quit)
# Maximize icon
self.maxBtn = QPushButton(self)
self.maxBtn.setGeometry(self,336,0,32,32)
self.maxBtn.setFlat(True)
self.maxBtn.setStyleSheet('QPushButton{background-color: rgba(0,0,0,0.0)}')
self.maxBtn.setIcon(QIcon('img/max.png'))
self.maxBtn.setIconSize(QSize(14,14))
# Minimize Incon
self.minBtn = QPushButton(self)
self.minBtn.setGeometry(304,0,32,32)
self.minBtn.setFlat(True)
self.minBtn.setStyleSheet('QPushButton{background-color: rgba(0,0,0,0.0)}')
self.minBtn.setIcon(QIcon('img/min.png'))
self.minBtn.setIconSize(QSize(10,10))
def main():
app = QApplication()
win = Main()
win.show()
app.exec_()
if __name__ == "__main__":
main()
I want to fixed navbar on the left. So, I create instance of QVBoxLayout and add widget to my Layout. and I had searched google, stackoverflow. i Don't get any information about my problem
but I don't know how to set layout widget. please teach me. Thank you.
if you don't understand my text please tell me i will describe that
Version:
PySide 5.14.2.1
Python 3.7.7
The layouts are not visual elements, so they do not have any geometric element associated with them, such as the width size, the layout is a handle of size and positions.
In this case the solution is to establish a container with a fixed size and in that container place the buttons with the help of a layout:
class Main(QDialog):
def __init__(self):
super(Main, self).__init__()
self.ui()
# Group Of Drage Event
def mousePressEvent(self, event):
self.offset = event.pos()
def mouseMoveEvent(self, e):
x = e.globalX()
y = e.globalY()
x_w = self.offset.x()
y_w = self.offset.y()
self.move(x - x_w, y - y_w)
def ui(self):
# TitleBar
self.setWindowFlags(Qt.FramelessWindowHint)
# Window Size
self.setGeometry(600, 300, 400, 500)
# Window Background Color
self.BackGroundColor = QPalette()
self.BackGroundColor.setColor(QPalette.Background, QColor(255, 255, 255))
self.setPalette(self.BackGroundColor)
# NavBar Button
self.btn = QPushButton("Test")
self.btn1 = QPushButton("Test1")
left_container = QWidget(self)
left_container.setFixedWidth(100)
# NavBar layout
self.layout = QVBoxLayout(left_container)
self.layout.addWidget(self.btn)
self.layout.addWidget(self.btn1)
hlay = QHBoxLayout(self)
hlay.addWidget(left_container)
hlay.addStretch()
# Close img
self.closeBtn = QPushButton(self)
self.closeBtn.setGeometry(368, 0, 32, 32)
self.closeBtn.setFlat(True)
self.closeBtn.setStyleSheet("QPushButton{background-color: rgba(0,0,0,0.0)}")
self.closeBtn.setIcon(QIcon("img/close.png"))
self.closeBtn.setIconSize(QSize(10, 10))
self.closeBtn.clicked.connect(QCoreApplication.instance().quit)
# Maximize icon
self.maxBtn = QPushButton(self)
self.maxBtn.setGeometry(336, 0, 32, 32)
self.maxBtn.setFlat(True)
self.maxBtn.setStyleSheet("QPushButton{background-color: rgba(0,0,0,0.0)}")
self.maxBtn.setIcon(QIcon("img/max.png"))
self.maxBtn.setIconSize(QSize(14, 14))
# Minimize Incon
self.minBtn = QPushButton(self)
self.minBtn.setGeometry(304, 0, 32, 32)
self.minBtn.setFlat(True)
self.minBtn.setStyleSheet("QPushButton{background-color: rgba(0,0,0,0.0)}")
self.minBtn.setIcon(QIcon("img/min.png"))
self.minBtn.setIconSize(QSize(10, 10))
I am a newbie in PyQt5 and learning to use QListWidget in a project. My problem is when I put three PushButtons inside a QListWidget. But when I click the buttons, nothing happened, and I cannot find the problem why.
So, could someone help me out? Thank you very much, and the following is my entire codes.
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'Main Window'
self.left = 300
self.top = 300
self.width = 840
self.height = 580
self.Contents = QStackedWidget()
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# the following is to create a ToolBar
self.toolbar = QToolBar()
self.toolbar.setStyleSheet("background-color: rgb(200, 155, 155);" 'spacing:20px;')
self.toolbar.setFixedHeight(86)
self.toolbar.setMovable( False)
# create three pushbutton called Button1, Button2, Button3
Button1 = QPushButton(self)
Button1.setText("Home Button")
Button2 = QPushButton(self)
Button2.setText("Simulation")
Button3 = QPushButton(self)
Button3.setText("Practice")
# create QListWidget and add the buttons into it
self.itemN = QListWidgetItem()
self.funList = QListWidget()
self.widget = QWidget()
widgetLayout = QHBoxLayout()
widgetLayout.addWidget(Button1)
widgetLayout.addWidget(Button2)
widgetLayout.addWidget(Button3)
widgetLayout.addStretch()
widgetLayout.setSizeConstraint(QLayout.SetFixedSize)
self.widget.setLayout(widgetLayout)
self.funList.addItem(self.itemN)
self.funList.setItemWidget(self.itemN, self.widget)
self.funList.clicked.connect(self.clicked_check) # this click seems not working
#put the QlistWidget into the toolbar
self.toolbar.addWidget(self.widget)
vbox = QVBoxLayout()
vbox.addWidget(self.toolbar)
self.setLayout(vbox)
self.show()
#pyqtSlot()
def clicked_check(self):
alert = QMessageBox()
alert.setText('This Button works')
alert.exec_()
if not QApplication.instance():
app = QApplication(sys.argv)
else:
app = QApplication.instance()
ex = App()
sys.exit(app.exec_())
I did not understand what you want to do, but if you put self.funList in the layout, we get the following result:
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'Main Window'
self.left = 300
self.top = 100
self.width = 840
self.height = 380
self.Contents = QStackedWidget()
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# the following is to create a ToolBar
self.toolbar = QToolBar()
self.toolbar.setStyleSheet("background-color: rgb(200, 155, 155);" 'spacing:20px;')
self.toolbar.setFixedHeight(86)
self.toolbar.setMovable( False)
# create three pushbutton called Button1, Button2, Button3
Button1 = QPushButton(self)
Button1.setText("Home Button")
Button1.clicked.connect(lambda: print(Button1.text())) # +
Button2 = QPushButton(self)
Button2.setText("Simulation")
Button3 = QPushButton(self)
Button3.setText("Practice")
# create QListWidget and add the buttons into it
self.itemN = QListWidgetItem()
self.funList = QListWidget()
self.widget = QWidget()
# self.widget.setStyleSheet("background-color: rgb(255, 155, 000);")
# self.funList.setStyleSheet("background-color: rgb(255, 000, 155);")
widgetLayout = QHBoxLayout()
widgetLayout.addWidget(Button1)
widgetLayout.addWidget(Button2)
widgetLayout.addWidget(Button3)
widgetLayout.addStretch()
widgetLayout.setSizeConstraint(QLayout.SetFixedSize)
self.widget.setLayout(widgetLayout)
self.funList.addItem(self.itemN)
self.itemN.setSizeHint(self.widget.sizeHint())
self.funList.setItemWidget(self.itemN, self.widget)
self.funList.clicked.connect(self.clicked_check) # this click seems not working
#put the QlistWidget into the toolbar
self.toolbar.addWidget(self.widget)
vbox = QVBoxLayout(self)
vbox.addWidget(self.funList) # <<<-----<
vbox.addWidget(self.toolbar)
self.setLayout(vbox)
self.show()
#pyqtSlot()
def clicked_check(self):
alert = QMessageBox()
alert.setText('This Button works')
alert.exec_()
if not QApplication.instance():
app = QApplication(sys.argv)
else:
app = QApplication.instance()
ex = App()
sys.exit(app.exec_())
I am trying to achieve something like this in PySide: https://codepen.io/imprakash/pen/GgNMXO
What I want to do is create a child window frameless with a black overlay below.
I didn't succeed to create a child window frameless and the overlay...
This is a base code to replicate the HTML:
from PySide import QtCore, QtGui
import sys
class MainWindow(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.resize(800, 500)
self.button = QtGui.QPushButton("Click Me")
self.setLayout(QtGui.QVBoxLayout())
self.layout().addWidget(self.button)
# Connections
self.button.clicked.connect(self.displayOverlay)
def displayOverlay(self):
popup = QtGui.QDialog(self)
popup.setWindowFlags(QtCore.Qt.FramelessWindowHint)
popup.setLayout(QtGui.QHBoxLayout())
popup.layout().addWidget(QtGui.QLabel("HI"))
popup.show()
print "clicked"
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
If you comment the line with the FramelessWindowHint, the window comes, else nothing happen...
I really hope that someone could help me. Thank you for the time you spent to read my question.
I'll be using PyQt5 for this explanation. It might have some differences to PySide (which I'm not sure if its still maintained) and PyQt4, but it shouldn't be too hard to convert.
The following example has a parent widget which a few buttons. One of them (the obvious one) calls for the popup. I've prepared the example to deal with the parent resize but have not made any code regarding mouse events of dragging the popup (see mouseMoveEvent and mouseReleaseEvent for that).
So here is the code:
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
class TranslucentWidgetSignals(QtCore.QObject):
# SIGNALS
CLOSE = QtCore.pyqtSignal()
class TranslucentWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(TranslucentWidget, self).__init__(parent)
# make the window frameless
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
self.fillColor = QtGui.QColor(30, 30, 30, 120)
self.penColor = QtGui.QColor("#333333")
self.popup_fillColor = QtGui.QColor(240, 240, 240, 255)
self.popup_penColor = QtGui.QColor(200, 200, 200, 255)
self.close_btn = QtWidgets.QPushButton(self)
self.close_btn.setText("x")
font = QtGui.QFont()
font.setPixelSize(18)
font.setBold(True)
self.close_btn.setFont(font)
self.close_btn.setStyleSheet("background-color: rgb(0, 0, 0, 0)")
self.close_btn.setFixedSize(30, 30)
self.close_btn.clicked.connect(self._onclose)
self.SIGNALS = TranslucentWidgetSignals()
def resizeEvent(self, event):
s = self.size()
popup_width = 300
popup_height = 120
ow = int(s.width() / 2 - popup_width / 2)
oh = int(s.height() / 2 - popup_height / 2)
self.close_btn.move(ow + 265, oh + 5)
def paintEvent(self, event):
# This method is, in practice, drawing the contents of
# your window.
# get current window size
s = self.size()
qp = QtGui.QPainter()
qp.begin(self)
qp.setRenderHint(QtGui.QPainter.Antialiasing, True)
qp.setPen(self.penColor)
qp.setBrush(self.fillColor)
qp.drawRect(0, 0, s.width(), s.height())
# drawpopup
qp.setPen(self.popup_penColor)
qp.setBrush(self.popup_fillColor)
popup_width = 300
popup_height = 120
ow = int(s.width()/2-popup_width/2)
oh = int(s.height()/2-popup_height/2)
qp.drawRoundedRect(ow, oh, popup_width, popup_height, 5, 5)
font = QtGui.QFont()
font.setPixelSize(18)
font.setBold(True)
qp.setFont(font)
qp.setPen(QtGui.QColor(70, 70, 70))
tolw, tolh = 80, -5
qp.drawText(ow + int(popup_width/2) - tolw, oh + int(popup_height/2) - tolh, "Yep, I'm a pop up.")
qp.end()
def _onclose(self):
print("Close")
self.SIGNALS.CLOSE.emit()
class ParentWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ParentWidget, self).__init__(parent)
self._popup = QtWidgets.QPushButton("Gimme Popup!!!")
self._popup.setFixedSize(150, 40)
self._popup.clicked.connect(self._onpopup)
self._other1 = QtWidgets.QPushButton("A button")
self._other2 = QtWidgets.QPushButton("A button")
self._other3 = QtWidgets.QPushButton("A button")
self._other4 = QtWidgets.QPushButton("A button")
hbox = QtWidgets.QHBoxLayout()
hbox.addWidget(self._popup)
hbox.addWidget(self._other1)
hbox.addWidget(self._other2)
hbox.addWidget(self._other3)
hbox.addWidget(self._other4)
self.setLayout(hbox)
self._popframe = None
self._popflag = False
def resizeEvent(self, event):
if self._popflag:
self._popframe.move(0, 0)
self._popframe.resize(self.width(), self.height())
def _onpopup(self):
self._popframe = TranslucentWidget(self)
self._popframe.move(0, 0)
self._popframe.resize(self.width(), self.height())
self._popframe.SIGNALS.CLOSE.connect(self._closepopup)
self._popflag = True
self._popframe.show()
def _closepopup(self):
self._popframe.close()
self._popflag = False
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
main = ParentWidget()
main.resize(500, 500)
main.show()
sys.exit(app.exec_())
Which results in the following:
The logic is the following. You create an empty Widget and manually draw the background and popup (paintEvent). You add a button for closing the popup. For this you build a Signal and let the parent widget do the closing. This is important because you need to make the parent widget control some important elements of the popup (such as closing, resizng, etc.). You can add far more complexity but hopefully the example will suffice for starters.
Thanks to armatita, I succeed to get what I wanted. For now, there are some issues but it works and I get the result that I wanted.
I give you the code to the next who will be looking for the same thing.
from PySide import QtCore, QtGui
import sys
class CtmWidget(QtGui.QWidget):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.button = QtGui.QPushButton("Close Overlay")
self.setLayout(QtGui.QHBoxLayout())
self.layout().addWidget(self.button)
self.button.clicked.connect(self.hideOverlay)
def paintEvent(self, event):
painter = QtGui.QPainter()
painter.begin(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
path = QtGui.QPainterPath()
path.addRoundedRect(QtCore.QRectF(self.rect()), 10, 10)
mask = QtGui.QRegion(path.toFillPolygon().toPolygon())
pen = QtGui.QPen(QtCore.Qt.white, 1)
painter.setPen(pen)
painter.fillPath(path, QtCore.Qt.white)
painter.drawPath(path)
painter.end()
def hideOverlay(self):
self.parent().hide()
class Overlay(QtGui.QWidget):
def __init__(self, parent, widget):
QtGui.QWidget.__init__(self, parent)
palette = QtGui.QPalette(self.palette())
palette.setColor(palette.Background, QtCore.Qt.transparent)
self.setPalette(palette)
self.widget = widget
self.widget.setParent(self)
def paintEvent(self, event):
painter = QtGui.QPainter()
painter.begin(self)
painter.setRenderHint(QtGui.QPainter.Antialiasing)
painter.fillRect(event.rect(), QtGui.QBrush(QtGui.QColor(0, 0, 0, 127)))
painter.end()
def resizeEvent(self, event):
position_x = (self.frameGeometry().width()-self.widget.frameGeometry().width())/2
position_y = (self.frameGeometry().height()-self.widget.frameGeometry().height())/2
self.widget.move(position_x, position_y)
event.accept()
class MainWindow(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.resize(800, 500)
self.button = QtGui.QPushButton("Click Me")
self.setLayout(QtGui.QVBoxLayout())
self.layout().addWidget(self.button)
self.popup = Overlay(self, CtmWidget())
self.popup.hide()
# Connections
self.button.clicked.connect(self.displayOverlay)
def displayOverlay(self):
self.popup.show()
print "clicked"
def resizeEvent(self, event):
self.popup.resize(event.size())
event.accept()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
Once again thank you both of you(ymmx and armatita) to spend time on my issue.
did you try replacing popup.show() by popup.exec_()? and remove self as a parameter of the Qdialog? I change QDialog to QmessageBox to be able to quit the subwindow but it still work with the QDialog.
popup = QMessageBox()
popup.setWindowFlags( Qt.FramelessWindowHint)
popup.setLayout( QHBoxLayout())
popup.layout().addWidget( QLabel("HI"))
popup.exec_()
update
class Popup(QDialog ):
def __init__(self):
super().__init__()
self.setWindowFlags( Qt.CustomizeWindowHint)
self.setLayout( QHBoxLayout())
Button_close = QPushButton('close')
self.layout().addWidget( QLabel("HI"))
self.layout().addWidget( Button_close)
Button_close.clicked.connect( self.close )
self.exec_()
print("clicked")
def mousePressEvent(self, event):
self.oldPos = event.globalPos()
def mouseMoveEvent(self, event):
delta = QPoint (event.globalPos() - self.oldPos)
#print(delta)
self.move(self.x() + delta.x(), self.y() + delta.y())
self.oldPos = event.globalPos()
class MainWindow( QWidget):
def __init__(self):
QWidget.__init__(self)
self.resize(800, 500)
self.button = QPushButton("Click Me")
self.setLayout( QVBoxLayout())
self.layout().addWidget(self.button)
# Connections
self.button.clicked.connect(self.displayOverlay)
def displayOverlay(self):
Popup( )
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
I have some buttons that I want to keep seperated from other elements in a widget. I'd like to put a frame around them but I'm not sure how.
import sys
from PyQt4 import QtGui, QtCore
class PasswordPrompt(QtGui.QWidget):
def __init__(self):
super(PasswordPrompt, self).__init__()
self.initUi()
def initUi(self):
self.setFixedSize(1000, 500)
self.setWindowTitle('Please enter the password...')
hbox = QtGui.QHBoxLayout()
vbox = QtGui.QVBoxLayout()
btn1 = QtGui.QPushButton("1")
btn2 = QtGui.QPushButton("2")
btn3 = QtGui.QPushButton("3")
vbox.addWidget(btn1)
vbox.addWidget(btn2)
vbox.addWidget(btn3)
vbox.setSpacing(0)
hbox.addLayout(vbox)
self.setLayout(hbox)
self.center()
self.show()
def center(self):
qr = self.frameGeometry()
cp = QtGui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def main():
application = QtGui.QApplication(sys.argv)
p = PasswordPrompt()
sys.exit(application.exec())
if __name__=='__main__':
main()
As an example, how would I add a black frame around these buttons? Thanks for any help.
QGroupBox can be used to set the outlines.
import sys
from PyQt4 import QtGui, QtCore
class PasswordPrompt(QtGui.QWidget):
def __init__(self):
super(PasswordPrompt, self).__init__()
self.initUi()
def initUi(self):
layout = QtGui.QVBoxLayout()
self.setLayout(layout)
groupBox1 = QtGui.QGroupBox('Button 1')
groupBox1Layout=QtGui.QVBoxLayout()
groupBox1.setLayout(groupBox1Layout)
btn1 = QtGui.QPushButton("1")
groupBox1Layout.addWidget(btn1)
groupBox2 = QtGui.QGroupBox('Button 2')
groupBox2Layout=QtGui.QVBoxLayout()
groupBox2.setLayout(groupBox2Layout)
btn2 = QtGui.QPushButton("2")
groupBox2Layout.addWidget(btn2)
groupBox3 = QtGui.QGroupBox('Button 3')
groupBox3Layout=QtGui.QVBoxLayout()
groupBox3.setLayout(groupBox3Layout)
btn3 = QtGui.QPushButton("3")
groupBox3Layout.addWidget(btn3)
layout.addWidget(groupBox1)
layout.addWidget(groupBox2)
layout.addWidget(groupBox3)
self.resize(300, 100)
self.show()
def main():
application = QtGui.QApplication(sys.argv)
p = PasswordPrompt()
sys.exit(application.exec_())
if __name__=='__main__':
main()