What widget is QtWidgets.QWidget() returning? [duplicate] - python

This question already has answers here:
What is the rule for choosing "central widget" in QMainWindow? and why is it important?
(2 answers)
Closed 1 year ago.
I am trying to learn PyQt to develop a GUI for viewing images. I found some code that looked like It could be easily converted to fit my use case. Figured going line by line to check the logic would help me understand PyQt.
I am getting stuck at this line in the following class
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QFileDialog
class Ui_MainWindow(QtWidgets.QMainWindow):
def __init__(self, imgs_path,masks_path, pred_path, study):
super(Ui_MainWindow, self).__init__()
# sets up ui
self.setObjectName("MainWindow")
self.resize(1440, 1000)
self.centralwidget = QtWidgets.QWidget()
self.centralwidget.setObjectName("centralwidget")
....
self.setCentralWidget(self.centralwidget)
The line which goes self.setCentralWidget(self.centralwidget), what exactly is being set as the central widget? I tried to look at the documentation but wasn't able to understand what was being set as the central widget. It looks like QtWidgets.QtWidget() is just a class containing methods for user interface?
The tutorial I was following introduced self.centralwidget in the context of setting it to some type of widget like QtWidgets.Qlabel() etc, so I am not sure what is actually being set as the central widget in this case.

I'll try to explain it to you visually:
In the picture, you can see the main frame, your QtWidgets.QMainWindow which, in this case, is the parent container to all the objects you'll place in your UI.
Then you have that highlighted rectangle in the middle, which is actually a QtWidgets.QWidget(). The fact that you are setting it as Centralwidget I think is more of a positional constrain/indication. In turn, QtWidgets.QWidget() can contains other elements (even another QtWidgets.QWidget() for example).

Related

Error Unresolved attribute reference 'pushButton' for class in pycharm [duplicate]

This question already has answers here:
Autocomplete from .ui
(4 answers)
reading UI file and connecting elements such as buttons, text, etc
(1 answer)
Closed 2 years ago.
I am working on pyqt5 project where I am designing the ui in qt designer and writing its python code in pycharm. Ui has a button and label. Once button is clicked, label value is changed. Below is the code:
import sys
from PyQt5.uic import loadUi
from PyQt5.QtWidgets import QApplication, QMainWindow
class ROCKET(QMainWindow):
def __init__(self):
super(ROCKET, self).__init__()
loadUi('ui/gui.ui', self)
self.pushButton.clicked.connect(self.btn_click)
def btn_click(self):
self.label.setText("CLICKED")
app = QApplication(sys.argv)
window = ROCKET()
window.show()
app.exec_()
Pycharm gives warning for pushButton and label:
Unresolved attribute reference 'pushButton' for class 'ROCKET'
but if I am running the code, I am getting correct output. How can I remove these warnings and make the code correct.
The fact that you can refer to your widgets as attributes of the main window is a convenience that is offered by PyQt5 via loadUi. PyCharm is complaining because it didn't see you explicitly define the pushButton attribute for your class.
One way you can get around the warning would be to explicitly define the attribute:
self.pushButton = self.findChild(QPushButton, "name_of_push_button")
self.pushButton.clicked.connect(self.btn_click)

How to show tooltip while not focusing at pyqt5 python?

I want to show tooltip while not focusing.
I made the code by referring to this PyQt Window Focus
But, it works after click window just one. Works fine, but window always blink at taskbar.
And I think this method is inefficient.
I think it's as if os are not resting while waiting for task to come, but checking every moment for task to come.
This is a simple window window, so it won't use up the cpu much, but I want to code it more efficiently.
Is there any way to improve this?
Or this method right because focusoutEvent excuted only one? ( Cpu resource 0% )
If right, how can I remove blink at taskbar?
I check reference focusPolicy-prop
import sys, os
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.setFocusPolicy(QtCore.Qt.ClickFocus)
self.initUI()
def initUI(self):
vbox = QVBoxLayout()
vbox.addStretch(2)
btn = QPushButton("Test")
btn.setToolTip("This tooltip")
vbox.addWidget(btn)
vbox.addStretch(1)
self.setLayout(vbox)
self.setGeometry(300, 300, 300, 200)
self.show()
def focusOutEvent(self, event):
self.setFocus(True)
self.activateWindow()
self.raise_()
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = MyApp()
sys.exit(app.exec_())
You are having an XY problem: trying to find a solution (usually unorthodox and overly complicated) for a problem that is originated elsewhere.
What you want to do is to show tooltips even if the window is not focused, not to restore the focus of the window; to achieve this you must not reactivate the window when it loses focus (which not only is WRONG, but is both a wrong way and reason for doing so).
You just have to set the WA_AlwaysShowToolTips widget attribute on the top level window (and remove the unnecessary focusOutEvent override, obviously).
class MyApp(QWidget):
def __init__(self):
super().__init__()
self.setFocusPolicy(QtCore.Qt.ClickFocus)
self.initUI()
self.setAttribute(QtCore.Qt.WA_AlwaysShowToolTips, True)
Note that the attribute must be set on a widget that is a top level window, so, unless you're using a QMainWindow or you are absolutely sure that the QWidget will always be a window, it's usually better to do this instead:
self.window().setAttribute(QtCore.Qt.WA_AlwaysShowToolTips, True)
Besides that, the blinking is normal on windows, and has nothing to do with CPU usage:
activateWindow():
[...] On Windows, if you are calling this when the application is not currently the active one then it will not make it the active window. It will change the color of the taskbar entry to indicate that the window has changed in some way. This is because Microsoft does not allow an application to interrupt what the user is currently doing in another application.

Merge QgsMessageBar with ui file ?

I try merge QgsMessageBar with ma ui file
from ui_file import Ui_File
class MyClass(QDialog):
def __init__(self):
QDialog.__init__(self)
self.bar = QgsMessageBar()
self.ui = Ui_File()
self.ui.setupUi(self)
self.ui.pushButton_2.clicked.connect(self.run)
def run(self):
self.bar.pushMessage("Hello", "World", level=QgsMessageBar.INFO)
When I change 'bar' to 'ui' I get error:
'Ui_File' object has no attribute 'pushMessage'
Something is missing in ui file?
How to fix it?
The code in your example looks fine as it is, but you need to add the message-bar to the layout of the dialog.
How you do this will depend on what kind of layout the dialog has, and where you want the message-bar to appear. If the layout is QVBoxLayout, and you want the message-bar at the bottom of the dialog, just do:
self.layout().addWidget(self.bar)
and to put it at the top of the dialog, you would do:
self.layout().insertWidget(0, self.bar)
However, if the layout is a QHBoxLayout or QGridLayout, you will probably have to alter things in Qt Designer to get things to work properly. In particular, QGridLayout has no method for inserting widgets, so you would have to leave a space for the message-bar if you want it at the top of the dialog. You may also need to ensure that the message-bar spans the full width of the dialog. See the docs for QGridLayout.addWidget for more details.
For a QHBoxLayout it's much easier - just put the existing layout inside a QVBoxLayout layout, and proceeed as above.

accessing QtGui objects created by pyQt

So I'm quit new to working with UI in python. I'm not really grasping a core concept and i think this simple question will help flip on the light switch.
As seen in the code snippet below, I imported a ui file made in Qt. This ui has a pushbutton on it. How do I make a click event on that button? I have gone through tutorials on how to code a button and use it. I understand that. It is the question of how to access the objects and manipulate the objects that are created by the ui file. What i really want to do is see how to perform a function (or instantiate a class or whatever) when a button is clicked. that function being one that i wrote. baby steps though. any answers and elaborations would be appreciated.
import sys
from PyQt4 import QtGui, uic, QtCore
class MyWindow(QtGui.QMainWindow):
def __init__(self):
super(MyWindow, self).__init__()
uic.loadUi('myWidget.ui', self)
self.show()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = MyWindow()
sys.exit(app.exec_())
like i said. very simple question but I'm just not really grasping the core concept here. thanks you.
self.ui=uic.loadUi('curveViewer.ui', self)
#where `your_pushbutton` is the button name specified in your .ui file:
self.ui.your_pushbutton.clicked.connect(self.onBtnClicked)
or just:
uic.loadUi('curveViewer.ui', self)
self.your_pushbutton.clicked.connect(self.onBtnClicked)
then define method onBtnClicked inside your class MyWindow:
def onBtnClicked():
print 'pushbutton clicked'
see New-style Signal and Slot Support
btw, it's better to remove self.show(), and make it:
window = MyWindow()
window.show()

How to create full transparency in a QTextEdit

I have been trying for many days to figure out a way to create a transparent Qtextedit with opaque text. Because the term "transparency" is often ambiguous, I define Qtextedit"transparency" as being able to see the text in the Qtextedit overlaid upon whatever is directly behind the main window (such as the desktop background, windows media player etc.) If possible I would like to be able to set the transparency at various levels and cross system compatible, but this is not required.
I am an extreme beginner, as I have only been using pyqt4 for 3 weeks and python 3.x for a few months and this is all the experience with programming that I have obtained in my existence. I have been attempting to decipher the Pyqt documentation with regard to this matter, but it is written in a way that seems to assume that one has been a gui programer for decades, not to mention having knowlege of C++. Furthermore, when this question is asked online it never seems to be resolved in way that is either: a) well documented or b) generalizable
This is very surprising because it seems like a basic operation that people would want to do
This solution works but doesn't seem to be directly useful for anything but displaying transparent images. I also don't really understand it all that well, as simply changing the base class from QWidget to QMainWindow makes the whole thing fail
http://www.loopbacking.info/blog/2008/07/11/transparent-windows-howto/
The following link embodies the common ways people suggest to solve problems similar to this, their pitfalls and why they don't work, but unfortunately they use the C++ version of Qt and are also a bit advanced for my skills at this point.
http://www.qtcentre.org/threads/18072-How-to-set-Qt-window-transparent
My system is windows 7 ultimate 32 bit on a dell latitude d830 with a Quadro NVS 140 whose driver version is current as of this post (Verde 275.33) My version of Pyqt is 4.8 (PyQt-Py3.2-x86-gpl-4.8.5-1.exe Windows 32 bit installer) I am also using Python 3.2.1 (Open Source version)
A basic example of my code lies beneath with the relevant (and failed) lines commented out:
When I tried the commented out code the color I generally just saw blackness. Also, when I resized my windows the darkness would randomly change intensity and the display of the main window seemed to get corrupted when maximized.
I would greatly appreciate any help on this matter!
import sys
import PyQt4
from PyQt4 import QtGui, QtCore
class Transparent(QtGui.QMainWindow):
def __init__(self,parent = None):
QtGui.QMainWindow.__init__(self,parent)
self.initialize()
def initialize(self):
#self.colorset(self,'Window',200,255,100,20)
#self.colorset(self,'Base',200,255,100,20)
#self.setBackgroundRole(QtGui.QPalette.Base)
#self.setAttribute(QtCore.Qt.WA_NoSystemBackground)
#self.setAutoFillBackground(True)
#self.mask()
self.setWindowTitle("Chernobyl-like Failure")
self.answerlabel = QtGui.QLabel('Text Response Display')
self.answerlabel.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Raised)
self.answerlabel.setMinimumHeight(25)
self.questionlabel = QtGui.QLabel("Question:")
self.questionlabel.setFrameStyle(QtGui.QFrame.Panel | QtGui.QFrame.Raised)
self.questionbox = QtGui.QLineEdit()
self.questionbox.setMinimumWidth(500)
self.askbutton = QtGui.QPushButton("Ask it!")
self.historybox = QtGui.QTextEdit('Question & Answer history will be displayed here')
self.historybox.setReadOnly(True)
#self.colorset(self.historybox,'Base',200,255,100,127)
self.grid = QtGui.QGridLayout()
widgetlist = [['answerlabel',0,0,1,3],['questionlabel',1,0,1,1],
['questionbox',1,1,1,1],['askbutton',1,2,1,1],['historybox',2,0,1,3]]
for widget in widgetlist:
self.grid.addWidget(eval("self.{0}".format(widget[0])),*widget[1:])
self.centralwidget = QtGui.QFrame()
self.centralwidget.setFrameStyle(QtGui.QFrame.Box|QtGui.QFrame.Raised)
self.centralwidget.setLineWidth(5)
self.centralwidget.setLayout(self.grid)
#self.colorset(self.centralwidget,'Base',200,255,100,127)
self.setCentralWidget(self.centralwidget)
def colorset(self,widget,part,h,s,l,a):
pal = widget.palette()
color = QtGui.QColor()
color.setHsl(h,s,l,a)
pal.setColor(eval('QtGui.QPalette.{0}'.format(part)),color)
widget.setPalette(pal)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
main_window = Transparent()
main_window.show()
sys.exit(app.exec_())
To make your main window transparent, you have to set the Qt.WA_TranslucentBackground attribute (using setAttribute(Qt.WA_TranslucentBackground)). Under Windows, you also must set the Qt.FramelessWindowHint attribute on your main window. According to the docs, however, "The user cannot move or resize a borderless window via the window system." So, if you want that functionality, you have to implement it manually. Here is a thread giving an example of that in C++.
Once you have a transparent MainWindow you can control the opacity of it and any child widgets by setting the background color to an RGBA value. Here is a dumb example,
from PyQt4 import QtGui, QtCore
import sys
class Main(QtGui.QMainWindow):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
frame = QtGui.QFrame(parent=self)
frame.setStyleSheet("QFrame {background: rgba(0,255,0,20%)}")
box=QtGui.QHBoxLayout()
edit = QtGui.QTextEdit()
edit.setStyleSheet("background: rgba(0,0,255,20%)")
box.addWidget(edit)
edit2=QtGui.QTextEdit()
edit2.setStyleSheet("background: rgb(255,0,0)")
box.addWidget(edit2)
frame.setLayout(box)
pushbutton = QtGui.QPushButton('Quit')
pushbutton.clicked.connect(self.close)
box.addWidget(pushbutton)
self.setCentralWidget(frame)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = Main()
main.show()
app.exec_()

Categories

Resources