Getting very stuck here, I am trying to learn how to use classes, and so simply want to show a button on a window when the button is in a different class. Here is the code I am trying to use:
#!/usr/bin/python3
import sys
from PyQt4 import QtGui, QtCore
class Window(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(0, 0, 800, 600)
main_menu = Menu()
self.show()
class Menu(QtGui.QWidget):
def __init__(self):
btn = QtGui.QPushButton("Quit")
btn.resize(btn.sizeHint())
btn.move(100,100)
btn.show()
print("Hello I am a menu")
def main():
app = QtGui.QApplication(sys.argv)
main_window = Window()
sys.exit(app.exec())
if __name__ == "__main__":
main()
This works so far as I get a window, but no button on it, howerver the print message I put in works. What am I doing wrong please?
You must initialize the parent class in Menu, in addition to passing the parent to that class and the button.
import sys
from PyQt4 import QtGui, QtCore
class Window(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.setGeometry(0, 0, 800, 600)
main_menu = Menu(self)
self.show()
class Menu(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
btn = QtGui.QPushButton("Quit", self)
btn.resize(btn.sizeHint())
btn.move(100,100)
print("Hello I am a menu")
def main():
app = QtGui.QApplication(sys.argv)
main_window = Window()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
Related
I open the dialog from the main window, where by clamping the keys, I fill the line with their names. The problem is that I can not understand where you need to do a cycle of checking all the keys on their state. Maybe there is another way to get the keys pressed? Or where you need to listen to the clamping so that the dialog box does not hang and the string is updated.
MainWindow:
def showBindings(self, param):
from dialogs import KeyBindingsDialog
self.dialog = KeyBindingsDialog()
self.dialog.show()
Dialog:
class KeyBindingsDialog(QtWidgets.QDialog):
def __init__(self, parent=None):
super(KeyBindingsDialog, self).__init__(parent)
self.ui = KeyBindings()
self.ui.setupUi(self)
Use QKeySequenceEdit:
from PyQt5 import QtCore, QtGui, QtWidgets
class KeySequenceEdit(QtWidgets.QKeySequenceEdit):
def keyPressEvent(self, event):
super(KeySequenceEdit, self).keyPressEvent(event)
seq_string = self.keySequence().toString(QtGui.QKeySequence.NativeText)
if seq_string:
last_seq = seq_string.split(",")[-1].strip()
le = self.findChild(QtWidgets.QLineEdit, "qt_keysequenceedit_lineedit")
self.setKeySequence(QtGui.QKeySequence(last_seq))
le.setText(last_seq)
self.editingFinished.emit()
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self._keysequenceedit = KeySequenceEdit(editingFinished=self.on_editingFinished)
button = QtWidgets.QPushButton("clear", clicked=self._keysequenceedit.clear)
hlay = QtWidgets.QHBoxLayout(self)
hlay.addWidget(self._keysequenceedit)
hlay.addWidget(button)
#QtCore.pyqtSlot()
def on_editingFinished(self):
sequence = self._keysequenceedit.keySequence()
seq_string = sequence.toString(QtGui.QKeySequence.NativeText)
print("sequence: ", seq_string)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
I was trying to set a shortcut for dropdown menu. The code is below
import sys
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtWidgets import QAction
class SystemTrayIcon(QtWidgets.QSystemTrayIcon):
def __init__(self, icon, parent=None):
super(SystemTrayIcon, self).__init__(icon, parent)
menu = QtWidgets.QMenu(parent)
# add actions and shortcuts for them.
exitAction = QAction('Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.triggered.connect(parent.close)
menu.addAction(exitAction)
restoreAction = QAction('Restore', self)
restoreAction.setShortcut("Ctrl+R")
restoreAction.triggered.connect(self.restore)
menu.addAction(restoreAction)
self.setContextMenu(menu)
def restore(self):
print 'restore'
class MainWindow(QtWidgets.QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Icon')
self.tray_icon = SystemTrayIcon(QtGui.QIcon('/opt/WizNote/wiznote.png'), self)
self.tray_icon.show()
self.show()
if __name__ == '__main__':
app = QtWidgets.QApplication([])
w = MainWindow()
sys.exit(app.exec_())
The shortcut doesn't work. Is there something wrong with my code?
Python2.7 and PyQt5 was installed in my laptop.
I had exactly the same problem as yours, and I solved it by respecting the following pattern for each action:
menu.addAction(exitAction)
parent.addAction(exitAction) # line to be added
Example code I am using:
import sys
from PyQt5 import QtCore
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.open_about = False
self.openAction = QtWidgets.QAction('About', self)
self.openAction.triggered.connect(self.aboutDialog)
menuBar = self.menuBar()
fileMenu = menuBar.addMenu('&File')
fileMenu.addAction(self.openAction)
self.calendar = QtWidgets.QCalendarWidget(self)
self.setCentralWidget(self.calendar)
def about_state_upd(self, value):
self.open_about = value
def aboutDialog(self):
self._about = AboutDialog(self)
self._about.exec_()
def hideEvent(self, hideEvent):
if self.open_about == True:
self._about.setVisible(False)
def showEvent(self, showEvent):
if self.open_about == True:
if self._about.isHidden() == True:
self._about.setModal(True)
self._about.setVisible(True)
class AboutDialog(QtWidgets.QDialog):
def __init__(self, parent):
super(AboutDialog, self).__init__(parent)
self.setMinimumSize(400, 350)
self.parent().about_state_upd(True)
def closeEvent(self, closeEvent):
self.parent().about_state_upd(False)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
app_window = MainWindow()
app_window.showMaximized()
sys.exit(app.exec_())
This code basically works, but seems very complicated. Is there a simpler / cleaner way to make it so that when the modal QDialog is open, if the QMainWindow is minimized, the QDialog also gets minimized too (and reverse when QMainWindow is restored)?
Code is running on KDE Neon (Kubuntu-based distro).
May be you can use this: http://korbinin.blogspot.fr/search/label/minimize%20button
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class MainForm(QDialog):
def __init__(self, fn=None,parent=None):
super(MainForm, self).__init__(parent,\
flags=Qt.WindowMinimizeButtonHint|Qt.WindowMaximizeButtonHint)
Thanks to the people on the PyQt Mailing list, I managed to get a workaround for KDE. Instead of using exec_(), I am just using show() - then I use setDisabled() on QMainWindow to make dialog act in a modal fashion. Here is a (very quick and basic) example for anyone interested:
import sys
from PyQt5 import QtCore
from PyQt5 import QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.openAction = QtWidgets.QAction('About', self)
self.openAction.triggered.connect(self.aboutDialog)
menuBar = self.menuBar()
fileMenu = menuBar.addMenu('&File')
fileMenu.addAction(self.openAction)
self.calendar = QtWidgets.QCalendarWidget(self)
self.setCentralWidget(self.calendar)
def aboutDialog(self):
self._about = AboutDialog(self)
self.setDisabled (True)
self._about.show()
def enableWidgets(self):
self.setDisabled(False)
class AboutDialog(QtWidgets.QDialog):
def __init__(self, parent):
super(AboutDialog, self).__init__(parent)
self.setMinimumSize(400, 350)
def closeEvent(self, parent):
self.parent().enableWidgets()
def changeEvent(self, event):
if event.type() == QtCore.QEvent.WindowStateChange:
if self.windowState() & QtCore.Qt.WindowMinimized:
self.parent().showMinimized()
else:
self.parent().showMaximized()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
app_window = MainWindow()
app_window.showMaximized()
sys.exit(app.exec_())
Link to PyQt Mailing List posts.
Look at the code
import sys
from PySide import QtCore, QtGui
class MyWidget(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.quit = QtGui.QPushButton("Quit", self)
self.setGeometry(300, 300, 250, 150)
self.statusBar().showMessage('Ready')
app = QtGui.QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())
Now all I want to do , is add a Status. Now status is available in QtGui.QMainWindow
How can i use this fact to add it in the above program? In pyside coding , seems like for every component , we need to make a class and some connect to the main class..whata s the theory here?
I tried myself like this , but it did not work.
import sys
from PySide import QtCore, QtGui
class MyWidget(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.quit = QtGui.QPushButton("Quit", self)
self.setGeometry(300, 300, 250, 150)
self.statusBar().showMessage('Ready')
self.s = MyStatus()
class MyStatus(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.statusBar().showMessage('Ready')
app = QtGui.QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())
You do not need to make a class for every component, but if you want to modify/override each component's built-in function you need to make a class for it.
To add something to your main window, you simply have to create an object and add it to the layout. As follow:
import sys
from PySide import QtGui , QtCore
class MyStatusBar(QtGui.QStatusBar):
def __init__(self, parent=None):
super(MyStatusBar, self).__init__(parent)
#Override any functions, or define new function for our status bar here
class MyMainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
#Set the size of the window
self.setMinimumSize(300,300)
#Create a status bar, from our OWN class
self.status_bar = MyStatusBar(self)
self.status_bar.setGeometry(QtCore.QRect(0, 0, 50, 50))
self.status_bar.showMessage('Ready')
#Add a simple quit button, from the DEFAULT class
self.quit_button = QtGui.QPushButton(self)
self.quit_button.clicked.connect(self.close)
self.quit_button.setGeometry(QtCore.QRect(100, 100, 100, 35))
self.quit_button.setText("Close")
#Start the application
app = QtGui.QApplication(sys.argv)
top = MyMainWindow()
top.show()
app.exec_()
If you want a window with a status-bar, use QMainWindow: it has one built-in (and also a menu-bar, tool-bars, dock-widgets, etc). Other widgets don't have these built-in features, and so, quite naturally, they don't have things like a statusBar method. If you insist on doing things the hard way by not using QMainWindow, you will have to add all these features yourself.
Although I wouldn't recommend doing things this way, here is a simple demo that adds a status-bar to a QWidget:
import sys
from PySide import QtCore, QtGui
class MyWidget(QtGui.QWidget):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.central_widget = QtGui.QWidget(self)
self.quit = QtGui.QPushButton("Quit", self)
self.setGeometry(300, 300, 250, 150)
layout = QtGui.QVBoxLayout(self.central_widget)
layout.addWidget(self.quit)
self.status = QtGui.QStatusBar(self)
layout = QtGui.QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.widget)
layout.addStretch()
layout.addWidget(self.status)
self.status.showMessage('Ready')
app = QtGui.QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())
I am trying to run class AddTQuestions from a def in class AddTest but it wont work!! It opens the window AddTQuestions for a split-second then closes it straight away?!
The code is shown here:
import sys
from PyQt4 import QtCore, QtGui
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
RunClassAction = QtGui.QAction(QtGui.QIcon('exit24.png'), 'Exit', self)
RunClassAction.triggered.connect(self.run)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(RunClassAction)
self.setGeometry(300, 300, 300, 200)
self.setWindowTitle('Why Wont this Woooorkkkkk')
self.show()
def run(self):
AddQuestion = AddTQuestions()
AddQuestion.show()
class AddTQuestions(QtGui.QMainWindow):
def __init__(self, parent=None):
super(AddTQuestions, self).__init__(parent)
self.welldone = QtGui.QLabel('WellDone')
self.button = QtGui.QPushButton('Press Me')
layout = QtGui.QVBoxLayout()
layout.addWidget(self.welldone)
layout.addWidget(self.button)
self.setLayout(layout)
print("hello")
if __name__ == '__main__':
app = QtGui.QApplication([])
window = Example()
window.show()
app.exec_()
The object get's garbage collected, since you don't hold any reference to it when the function ends.
add them as class variables like this and the window stays open.
self.AddQuestion = AddTQuestions()
self.AddQuestion.show()