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_())
Related
I tried to use 'pywinauto' package and it works. But when I close app, python prompts an message "python has
stopped working". I added sys.coinit_flags = 2 as suggested by Vasily Ryabov, the warning disappeared.
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
import sys
import warnings
warnings.simplefilter("ignore", UserWarning)
sys.coinit_flags = 2
from pywinauto.application import Application
from pywinauto.keyboard import send_keys
class App(QWidget):
def __init__(self):
super(App,self).__init__()
self.title = 'PyQt5 button - pythonspot.com'
self.left = 10
self.top = 100
self.width = 320
self.height = 200
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
button = QPushButton('PyQt5 button', self)
button.setToolTip('This is an example button')
button.move(100, 70)
button.clicked.connect(self.on_click)
self.show()
def on_click(self):
print('PyQt5 button click')
def main():
app = QApplication(sys.argv)
app.setStyle('Fusion')
w = App()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
But when I tried to make the code complex, the warning message was prompted again if I clicked on first combo box to select value 'ar-prod'.
from PyQt5.QtCore import Qt
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
import warnings
warnings.simplefilter("ignore", UserWarning)
sys.coinit_flags = 2
from pywinauto.application import Application
from pywinauto.keyboard import send_keys
def main():
app = QApplication(sys.argv)
w = myView()
w.show()
sys.exit(app.exec_())
class myView(QWidget):
def __init__(self):
super(myView, self).__init__()
self.setGeometry(400, 200, 1000, 700)
self.mainLayout = QVBoxLayout()
self.splitter1 = QSplitter(Qt.Horizontal)
# Add ComboBox
self.cb1=QComboBox() #ar-dev or ar-prod
self.cb1.addItems(['ar-dev','ar-prod'])
self.cb2=QComboBox() #ar-dev/.
self.cb3=QComboBox() #ar-dev/..
self.cb4=QComboBox() #ar-dev/...
self.btn=QPushButton('Launch SAS EG')
self.splitter1.addWidget(self.cb1)
self.splitter1.addWidget(self.cb2)
self.splitter1.addWidget(self.cb3)
self.splitter1.addWidget(self.cb4)
self.splitter1.addWidget(self.btn)
# Add list of folders
self.splitter2 = QSplitter(Qt.Vertical)
self.bottomleft_layout = QHBoxLayout()
self.GroupBox1 = QGroupBox("")
self.table = QTableWidget()
self.table.verticalHeader().setVisible(False)
self.table.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # close vertical scroll bar
self.table.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # close horizontal scroll bar
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
self.table.verticalHeader().setSectionResizeMode(QHeaderView.Stretch)
self.hfont = QFont('Times New Roman', 12)
self.hfont.setBold(True)
self.table.horizontalHeader().setFont(self.hfont)
style = "::section {""background-color: lightgray; }"
self.table.horizontalHeader().setStyleSheet(style)
self.table.horizontalHeader().setFixedHeight(50)
self.bottomleft_layout.addWidget(self.table)
self.GroupBox1.setLayout(self.bottomleft_layout)
# Add Autoexec
self.GroupBox2 = QGroupBox("")
self.bottomright_layout = QVBoxLayout()
self.textEdit = QTextEdit()
self.bottomright_layout.addWidget(self.textEdit)
self.GroupBox2.setLayout(self.bottomright_layout)
self.tabs = QTabWidget()
self.tabs.addTab(self.GroupBox1, 'Hyperlinks to Sub Folders')
self.tabs.addTab(self.GroupBox2, 'Autoexec')
self.splitter2.addWidget(self.tabs)
self.mainLayout.addWidget(self.splitter1)
self.mainLayout.addWidget(self.splitter2)
self.setLayout(self.mainLayout)
if __name__ == '__main__':
main()
Here is the warning message.
If I remove self.cb1.addItems(['ar-dev', 'ar-prod']) and do not populate first combo box, the error will not occur.
You need sys.coinit_flags = 2 before importing pywinauto. Like it is shown here: https://github.com/pywinauto/py_inspect/blob/master/py_inspect.py
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)
Trying to remove a qwidget and replace it with another qwidget and then reload the layout the qwidget is a part of
I've already tried the update and removeWidget method, though i could've used it improperly
from PyQt5.Qt import *
import sys
validUser = False
app = None
class App(QMainWindow):
def __init__(self):
super().__init__()
screen = app.primaryScreen().size()
self.title = 'Restaurant Application'
width = screen.width()
height = screen.height()
self.left = 0
self.top = 0
self.width = width
self.height = height
self.setMouseTracking(True)
self.table_widget = MyTableWidget(self)
self.setCentralWidget(self.table_widget)
self.initUI()
self.show()
def initUI(self):
# window
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# statusbar
self.statusBar().showMessage('Welcome to el restaurante')
def mousePressEvent(self, event):
print('Mouse coords: ( %d : %d )' % (event.x(), event.y()))
class MyTableWidget(QWidget):
def __init__(self, parent):
super(QWidget, self).__init__(parent)
self.layout = QVBoxLayout(self)
# Initialize tab screen
self.tabs = QTabWidget()
self.login = QWidget()
self.menu = QWidget()
self.checkOut = QWidget()
self.tabs.resize(500, 200)
# Add tabs
self.tabs.addTab(self.login, "Login")
self.tabs.addTab(self.menu, "Menu")
self.tabs.addTab(self.checkOut, "Check out")
# Create login tab
self.login.layout = QVBoxLayout(self)
self.menu.layout = QVBoxLayout(self)
# login text
self.loginPrompt = QLabel("Please provide a valid login")
self.loginPrompt.setFixedSize(315,30)
self.loginPromptFont = QFont("Times", 27, QFont.Bold)
self.loginPrompt.setFont(self.loginPromptFont)
self.login.layout.addWidget(self.loginPrompt)
self.login.setLayout(self.login.layout)
# Create textbox
self.loginTextbox = QLineEdit(self)
self.loginTextbox.returnPressed.connect(self.on_click_login)
self.loginTextbox.setFixedSize(170,20)
# Create a button in the window
self.loginButton = QPushButton('Login button', self)
self.loginButton.clicked.connect(self.on_click_login)
self.loginButton.setFixedSize(100,40)
self.login.layout.addWidget(self.loginTextbox,alignment=Qt.AlignCenter)
self.login.layout.addWidget(self.loginButton,alignment=Qt.AlignCenter)
#widget code i use to decide which widget to add
self.menuInvalidUserLogin = QLabel("Please login in to view")
self.menuValidUserLogin = QLabel("Here's the menu")
if(validUser):
self.menu.layout.addWidget(self.menuValidUserLogin)
else:
self.menu.layout.addWidget(self.menuInvalidUserLogin)
self.menu.setLayout(self.menu.layout)
# Add tabs to widget
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
def on_click_login(self):
global validUser
global app
textboxValue = self.loginTextbox.text()
if(textboxValue.lower() == 'pass'):
validUser=True
#the solutions i have been trying
self.menu.layout.removeWidget(self.menuInvalidUserLogin)
self.layout.removeWidget(self.menuInvalidUserLogin)
self.menu.layout.update()
QMessageBox.question(self, 'Response', "Login successful: Welcome", QMessageBox.Ok,QMessageBox.Ok)
else:
validUser=False
QMessageBox.question(self, 'Response', "Login unsuccessful: EXPLAIN YOURSELF", QMessageBox.Ok,QMessageBox.Ok)
self.loginTextbox.setText("")
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
expected results should be that the old widget is removed, new widget is added and then the layout those widgets are a part of is refreshed
Is this what you were expecting?
Also, is there a specific reason why you are using global variables in your class? It is bad practice, you should make them class members.
from PyQt5 import QtWidgets, QtCore, QtGui
import sys
class App(QtWidgets.QMainWindow):
def __init__(self):
super(App,self).__init__()
app = QtWidgets.QApplication.instance()
screen = app.primaryScreen().size()
self.title = 'Restaurant Application'
width = screen.width()
height = screen.height()
self.left = 0
self.top = 0
self.width = width
self.height = height
self.setMouseTracking(True)
self.table_widget = MyTableWidget(self)
self.setCentralWidget(self.table_widget)
self.initUI()
self.show()
def initUI(self):
# window
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
# statusbar
self.statusBar().showMessage('Welcome to el restaurante')
def mousePressEvent(self, event):
print('Mouse coords: ( %d : %d )' % (event.x(), event.y()))
class MyTableWidget(QtWidgets.QWidget):
def __init__(self, parent):
super(MyTableWidget, self).__init__(parent)
self.layout = QtWidgets.QVBoxLayout()
self.validUser = False
# Initialize tab screen
self.tabs = QtWidgets.QTabWidget()
self.login = QtWidgets.QWidget()
self.menu = QtWidgets.QWidget()
self.checkOut = QtWidgets.QWidget()
self.tabs.resize(500, 200)
# Add tabs
self.tabs.addTab(self.login, "Login")
self.tabs.addTab(self.menu, "Menu")
self.tabs.addTab(self.checkOut, "Check out")
# Create login tab
self.login.layout = QtWidgets.QVBoxLayout()
self.menu.layout = QtWidgets.QVBoxLayout()
# login text
self.loginPrompt = QtWidgets.QLabel("Please provide a valid login")
self.loginPrompt.setFixedSize(315,30)
self.loginPromptFont = QtGui.QFont("Times", 27, QtGui.QFont.Bold)
self.loginPrompt.setFont(self.loginPromptFont)
self.login.layout.addWidget(self.loginPrompt)
self.login.setLayout(self.login.layout)
# Create textbox
self.loginTextbox = QtWidgets.QLineEdit()
self.loginTextbox.returnPressed.connect(self.on_click_login)
self.loginTextbox.setFixedSize(170,20)
# Create a button in the window
self.loginButton = QtWidgets.QPushButton('Login button')
self.loginButton.clicked.connect(self.on_click_login)
self.loginButton.setFixedSize(100,40)
self.login.layout.addWidget(self.loginTextbox,alignment=QtCore.Qt.AlignCenter)
self.login.layout.addWidget(self.loginButton,alignment=QtCore.Qt.AlignCenter)
#widget code i use to decide which widget to add
self.menuInvalidUserLogin = QtWidgets.QLabel("Please login in to view")
self.menuValidUserLogin = QtWidgets.QLabel("Here's the menu")
if(self.validUser):
self.menu.layout.addWidget(self.menuValidUserLogin)
else:
self.menu.layout.addWidget(self.menuInvalidUserLogin)
self.menu.setLayout(self.menu.layout)
# Add tabs to widget
self.layout.addWidget(self.tabs)
self.setLayout(self.layout)
def on_click_login(self):
textboxValue = self.loginTextbox.text()
if(textboxValue.lower() == 'pass'):
self.validUser=True
for i in reversed(range(self.menu.layout.count())):
widgetToRemove = self.menu.layout.itemAt(i).widget()
self.menu.layout.removeWidget(widgetToRemove)
widgetToRemove.deleteLater()
self.menu.layout.addWidget(self.menuValidUserLogin)
QtWidgets.QMessageBox.question(self, 'Response', "Login successful: Welcome", QtWidgets.QMessageBox.Ok,QtWidgets.QMessageBox.Ok)
self.tabs.setCurrentIndex(1)
else:
self.validUser=False
QtWidgets.QMessageBox.question(self, 'Response', "Login unsuccessful: EXPLAIN YOURSELF", QtWidgets.QMessageBox.Ok,QtWidgets.QMessageBox.Ok)
self.loginTextbox.setText("")
def main():
app = QtWidgets.QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
I want the first window that opens up to contain 4 push buttons responding to the numbers: 2,3,4,5. Once I have pressed one of these buttons I want the window to close and a new window to open with a label (just so I know it works) and also to use that number as a separate variable as it will select a sheet that I am reading from an excel file.
At the moment I can create the first window with the boxes, and when I press one the new window opens - but I cannot get the selection I made to come across.
Here is as far as I have got so far...
import sys
from PyQt5.QtWidgets import QApplication, QLabel, QPushButton, QHBoxLayout, QGroupBox, QDialog, QVBoxLayout, QMainWindow
# select floor window
class select_floor_window(QDialog):
def __init__(self, parent=None):
super().__init__()
self.title = 'Select floor'
self.left = 10
self.top = 10
self.width = 320
self.height = 100
self.selection_ui()
def selection_ui(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.createHorizontalLayout()
windowLayout = QVBoxLayout()
windowLayout.addWidget(self.horizontalGroupBox)
self.setLayout(windowLayout)
self.show()
def createHorizontalLayout(self):
# box layout
self.horizontalGroupBox = QGroupBox("Which floor are you on?")
layout = QHBoxLayout()
# floor buttons
floor_2_button = QPushButton("2", self)
floor_2_button.clicked.connect(self.on_click2)
layout.addWidget(floor_2_button)
floor_3_button = QPushButton("3", self)
floor_3_button.clicked.connect(self.on_click3)
layout.addWidget(floor_3_button)
floor_4_button = QPushButton("4", self)
floor_4_button.clicked.connect(self.on_click4)
layout.addWidget(floor_4_button)
floor_5_button = QPushButton("5", self)
floor_5_button.clicked.connect(self.on_click5)
layout.addWidget(floor_5_button)
self.horizontalGroupBox.setLayout(layout)
# close this window and load main window
def on_click2(self):
self.floorchoice = 2
self.show_main = main_Window()
self.show_main.show()
self.hide()
print("2")
return floorchoice
def on_click3(self):
self.floorchoice = 3
self.show_main = main_Window()
self.show_main.show()
self.hide()
print("3")
return floorchoice
def on_click4(self):
self.floorchoice = 4
self.show_main = main_Window()
self.show_main.show()
self.hide()
print("4")
return floorchoice
def on_click5(self):
self.floorchoice = 5
self.show_main = main_Window()
self.show_main.show()
self.hide()
print("5")
return floorchoice
# create main window
class main_Window(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.title = "2ndwindow"
self.top = 100
self.left = 100
self.width = 680
self.height = 500
show_floor_button = QLabel(floorchoice, self)
show_floor_button.move(100,100)
# Close app button
close_app_button = QPushButton("Exit", self)
close_app_button.move(400,400)
close_app_button.setToolTip("Close application")
close_app_button.clicked.connect(self.CloseApp)
self.InitWindow()
# showing window
def InitWindow(self):
self.setWindowTitle(self.title)
self.setGeometry(self.top, self.left, self.width, self.height)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = select_floor_window()
sys.exit(app.exec_())
Anyway that I try to set up the code, it always says that "name 'floorchoice' is not defined" in the second window, and cannot get it to display the result from the first class.
The functions that are invoked do not return anything, plus self.floorchoice is different floorchoice, the first is an attribute of the class and the other is a local variable.
What you have to do is that the class through the constructor or another method get that information.
In the next one I add one more argument to the invocation using functool.partial, then I pass that argument to the constructor of the other window so that I get that information.
I think your main error is caused by not taking into account that each variable, instance, object, etc. has a scope within the application.
import sys
from PyQt5.QtWidgets import QApplication, QLabel, QPushButton, QHBoxLayout, QGroupBox, QDialog, QVBoxLayout, QMainWindow
from functools import partial
# select floor window
class select_floor_window(QDialog):
def __init__(self, parent=None):
super().__init__()
self.title = "Select floor"
self.left = 10
self.top = 10
self.width = 320
self.height = 100
self.selection_ui()
def selection_ui(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.createHorizontalLayout()
windowLayout = QVBoxLayout(self)
windowLayout.addWidget(self.horizontalGroupBox)
def createHorizontalLayout(self):
# box layout
self.horizontalGroupBox = QGroupBox("Which floor are you on?")
layout = QHBoxLayout()
self.horizontalGroupBox.setLayout(layout)
# floor buttons
for option in (2, 3, 4, 5):
button = QPushButton(str(option))
layout.addWidget(button)
wrapper = partial(self.on_click, option)
button.clicked.connect(wrapper)
# close this window and load main window
def on_click(self, option):
self.show_main = main_Window(option)
self.show_main.show()
self.hide()
# create main window
class main_Window(QMainWindow):
def __init__(self, option, parent=None):
super().__init__(parent)
self.title = "2ndwindow"
self.top = 100
self.left = 100
self.width = 680
self.height = 500
show_floor_button = QLabel(str(option), self)
show_floor_button.move(100, 100)
# Close app button
close_app_button = QPushButton("Exit", self)
close_app_button.move(400, 400)
close_app_button.setToolTip("Close application")
close_app_button.clicked.connect(self.close)
self.InitWindow()
# showing window
def InitWindow(self):
self.setWindowTitle(self.title)
self.setGeometry(self.top, self.left, self.width, self.height)
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = select_floor_window()
ex.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()