pyqt5 not showing window [duplicate] - python

This question already has answers here:
PyQt: app.exec_() stops all following code from running
(4 answers)
Should I use `app.exec()` or `app.exec_()` in my PyQt application?
(3 answers)
Closed 4 years ago.
I really hope someone can help me out on this one.
Im trying to get started with using pyqt5, and have pretty much copied this code from a course that i am taking. the code seems to execute without any problems, but the window that i should be seeing is simply not appearing, what am I doing wrong?
Im working on ubuntu 18 by the way
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class Page(QWidget):
def __init__(self, parent=None):
super(Page, self).__init__(parent)
my_label = QLabel("This is my labet")
layout = QVBoxLayout()
layout.addWidget(my_label)
mainLayout = QGridLayout()
mainLayout.addLayout(layout, 0, 1)
self.setLayout(mainLayout)
self.setWindowTitle("my first Qt app")
if __name__ == "__mongo__":
import sys
print("LOEREE")
app = QApplication(sys.argv)
window = Page()
window.show()

In your example there were some typos and at the end there was no line sys.exit (app.exec _ ()) which starts the main loop of the application. From here begins the processing of events.
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
class Page(QWidget):
def __init__(self, parent=None): # __init__
super(Page, self).__init__(parent) # __init__
my_label = QLabel("This is my labet")
layout = QVBoxLayout()
layout.addWidget(my_label)
mainLayout = QGridLayout()
mainLayout.addLayout(layout, 0, 1)
self.setLayout(mainLayout)
self.setWindowTitle("my first Qt app")
if __name__ == '__main__': #
import sys
print("LOEREE")
app = QApplication(sys.argv)
window = Page()
window.show()
sys.exit(app.exec_()) # !!!

Related

PyQt - how to rerender window

I am new to PyQt and Qt at all and I have a problem with window rendering or updating or how to call it. Problem is that when I call QWidget.show(), none of added components after are displayed. Here is a simple code, where in init(), there is called self.show(). First QLabel item is displayed and the second one is not. What am I doing wrong?
Code:
from PyQt6.QtWidgets import QApplication, QWidget, QLabel
import sys
class MyGui(QWidget):
box = {}
def __init__(self) -> None:
super().__init__()
self.setFixedSize(200, 400)
self.setStyleSheet("background-color:#000000")
self.box["top"] = QLabel(self)
self.box["top"].setFixedSize(200, 200)
self.box["top"].setStyleSheet("background-color:red")
self.box["top"].move(0,0)
self.show()
self.box["botom"] = QLabel(self)
self.box["botom"].setFixedSize(200, 200)
self.box["botom"].setStyleSheet("background-color:green")
self.box["botom"].move(0,200)
if __name__ == "__main__":
app = QApplication(sys.argv)
my_app = MyGui()
my_app.show()
try:
sys.exit(app.exec())
except SystemExit:
print("Closing window..")
Screenshots of GUI window:
With self.show()
Without self.show()

PyQt5: Closeable tabs in QTabWidget? [duplicate]

This question already has an answer here:
connect function in pyqt5 does not work
(1 answer)
Closed 2 years ago.
I have been trying to implement QTabWidget section in my application, and would like to be able to close the tabs if needed.
I read that I need to set the setTabsCloseable flag to true and add a pyqtSignal but I cannot do so because QObject has no connect attribute.
On the contrary most examples I have found online, mention the use of QtCore.QObject.Connect()
here is a minimum reproducible example:
from PyQt5 import QtWidgets, QtCore, QtWidgets
import sys, os
class Dialog_01(QtWidgets.QMainWindow):
def __init__(self):
super(Dialog_01,self).__init__()
mainWidget=QtWidgets.QWidget()
self.setCentralWidget(mainWidget)
mainLayout = QtWidgets.QVBoxLayout()
mainWidget.setLayout(mainLayout)
self.tabWidget = QtWidgets.QTabWidget()
self.tabWidget.setTabsClosable(True)
# QtCore.QObject.connect(self.chatView, QtCore.SIGNAL('tabCloseRequested(int)'), self.closeTab)
mainLayout.addWidget(self.tabWidget)
myBoxLayout = QtWidgets.QVBoxLayout()
self.tabWidget.setLayout(myBoxLayout)
self.tabWidget.addTab(QtWidgets.QWidget(),'Tab_01')
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())
You can super the QtabWidget to incorporate custom functionality and also keep things wrapped up nicely.
I have found it quite common to override classes to suit certain programs with PyQt /Pyside and I strongly suggest you get into the habit!
from PyQt5 import QtWidgets, QtCore, QtWidgets
import sys, os
class QCustomTabWidget (QtWidgets.QTabWidget):
def __init__ (self, parent = None):
super(QCustomTabWidget, self).__init__(parent)
self.setTabsClosable(True)
self.tabCloseRequested.connect(self.closeTab) # connect to method to close
for i in range(1, 10): # add tabs here
self.addTab(QtWidgets.QWidget(), 'Tab %d' % i)
def closeTab (self, currentIndex):
currentQWidget = self.widget(currentIndex)
currentQWidget.deleteLater()
self.removeTab(currentIndex)
class Dialog_01(QtWidgets.QMainWindow):
def __init__(self):
super(Dialog_01,self).__init__()
mainWidget=QtWidgets.QWidget()
self.setCentralWidget(mainWidget)
mainLayout = QtWidgets.QVBoxLayout()
mainWidget.setLayout(mainLayout)
self.tabWidget = QCustomTabWidget()
mainLayout.addWidget(self.tabWidget)
myBoxLayout = QtWidgets.QVBoxLayout()
self.tabWidget.setLayout(myBoxLayout)
self.tabWidget.addTab(QtWidgets.QTextEdit(),'Tab_01') #also add tabs here
self.tabWidget.addTab(QtWidgets.QTextEdit(),'Tab_02')
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())

How to make another window which has the same geometry (position and width, height) as the original window, to simulate that the entire page changed? [duplicate]

I'm just getting started with PyQt5. I have been trying to accomplish a seemingly very simple task but haven't been able to get enough info about it. After a fair bit of googling I have been able to get one window to close and another to launch with the other UI loaded but that's not what I want to do here.
I want to switch the UI in the same window. I am loading the UI files as global variables in my python file where I have 2 classes for each UI. When I click a particular button in one UI, I want to switch to the other UI in the same window. Below is a sample of the code:
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
from PyQt5.uic import loadUiType
import os
about_company_ui, _ = loadUiType(os.path.join('frontend', 'ui', 'about_company.ui'))
intern_placement_ui, _ = loadUiType(os.path.join('frontend', 'ui', 'intern_placement.ui'))
class InternPlacement(QMainWindow, intern_placement_ui):
def __init__(self):
QMainWindow.__init__(self)
self.setupUi(self)
self.intern_pushButton.clicked.connect(self.change)
def change(self):
self.about_company = AboutCompany()
self.about_company.show()
self.close()
class AboutCompany(QMainWindow, about_company_ui):
def __init__(self):
QMainWindow.__init__(self)
self.setupUi(self)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = InternPlacement()
window.show()
app.exec_()
You have to use a QStackedWidget
import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets, uic
ui_folder = os.path.join("frontend", "ui")
about_company_ui, _ = uic.loadUiType(os.path.join(ui_folder, "about_company.ui"))
intern_placement_ui, _ = uic.loadUiType(os.path.join(ui_folder, "intern_placement.ui"))
class InternPlacement(QtWidgets.QMainWindow, intern_placement_ui):
def __init__(self, parent=None):
super(InternPlacement, self).__init__(parent)
self.setupUi(self)
class AboutCompany(QtWidgets.QMainWindow, about_company_ui):
def __init__(self, parent=None):
super(AboutCompany, self).__init__(parent)
self.setupUi(self)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
intern_window = InternPlacement()
about_window = AboutCompany()
w = QtWidgets.QStackedWidget()
w.addWidget(intern_window)
w.addWidget(about_window)
intern_window.intern_pushButton.clicked.connect(lambda: w.setCurrentIndex(1))
w.resize(640, 480)
w.show()
sys.exit(app.exec_())

Unable to add a QTextEdit inside QTreeWidget

I'm trying to add an option for a QTreeWidget to have multi line editing, which I would assume will require a QTextEdit. The problem is that the examples I've found online just do not work.
The answers I've found have all pointed to using tree.setItemWidget(item, column, widget), but If I add that line, the window just doesn't appear at all. What am I doing wrong in this case?
Here is my example code that has the issue:
import sys
from Qt import QtWidgets, QtCore
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None, **kwargs):
super(MainWindow, self).__init__(parent, **kwargs)
#Add tree widget to window
tree = QtWidgets.QTreeWidget()
tree.setHeaderItem(QtWidgets.QTreeWidgetItem(['col1', 'col2']))
self.setCentralWidget(tree)
#Create items
topLevelButton = QtWidgets.QPushButton('button')
topLevelItem = QtWidgets.QTreeWidgetItem(['test button', 'line edit'])
topLevelItem.setFlags(topLevelItem.flags() | QtCore.Qt.ItemIsEditable)
#Add items to tree widget
tree.addTopLevelItem(topLevelItem)
tree.setItemWidget(topLevelItem, 0, topLevelButton) #the window will not load if this line is not commented out
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
app.setActiveWindow(window)
window.show()
sys.exit(app.exec_())
I've tried it in PySide (2.7) and PySide2 (3.7).
Edit: For Python 3 at least, it seemed to be an issue with PySide2, where forcing PyQt5 somehow fixed whatever it was. I'm still unable to launch with Python 2 as I can't really install PyQt4.
Edit 2: It actually causes a crash if you use it in a program such as Nuke that uses PySide, I may need to ask a more specific question if I can't figure it out from this one.
Sorry, PyQt5 is working.
import sys
#from Qt import QtWidgets, QtCore
from PyQt5 import QtWidgets, QtCore # <---
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None, **kwargs):
super(MainWindow, self).__init__(parent, **kwargs)
# Add tree widget to window
tree = QtWidgets.QTreeWidget()
tree.setHeaderItem(QtWidgets.QTreeWidgetItem(['col1', 'col2']))
self.setCentralWidget(tree)
# Create items
topLevelButton = QtWidgets.QPushButton('button')
topLevelItem = QtWidgets.QTreeWidgetItem(['test button', 'line edit'])
topLevelItem.setFlags(topLevelItem.flags() | QtCore.Qt.ItemIsEditable)
# Add items to tree widget
tree.addTopLevelItem(topLevelItem)
tree.setItemWidget(topLevelItem, 0, topLevelButton) # ??? the window will not load if this line is not commented out
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
app.setActiveWindow(window) # ???
window.show()
sys.exit(app.exec_())

How to make application window stay on top in pyqt5?

I'm trying to make a desktop application in pyqt5 that will stay on top of all windows. I've been looking around online and they all say that the solution is to set the window flags using the setWindowFlags(Qt.WindowStaysOnTopHint) method, but this isn't working for me. Is there some other way I can do this?
I'm on Windows 10 and using Python 3.6 + pyqt5 version 5.9.2. My code is as follows:
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys
class Main(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowFlags(Qt.WindowStaysOnTopHint)
self.initUI()
self.show()
def initUI(self):
self.alertWidget = AlertWidget()
self.setCentralWidget(self.alertWidget)
class AlertWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
grid = QGridLayout()
self.setLayout(grid)
grid.setAlignment(Qt.AlignTop)
self.alertTextBox = QTextEdit()
grid.addWidget(self.alertTextBox, 0, 0)
if __name__ == '__main__':
app = QApplication(sys.argv)
main = Main()
sys.exit(app.exec_())
Assuming the rest of your code is good, change the following line of code:
self.setWindowFlags(Qt.WindowStaysOnTopHint)
to the following line of code:
self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.CustomizeWindowHint | Qt.WindowStaysOnTopHint)
Link to an answer explaining why the code change above is required for the Qt.WindowStaysOnTop flag to work.

Categories

Resources