I use QT designer to design a page that contains two buttons, a start and an end, but when I click them, there is no response. I put them all in widgets, is that why?
I'm confused. When I click the start or end button,no Change!
PyQt5 When I click the QpushButton ,No change?
Is it because it's inside the widget?
My code is like this.
# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(640, 480)
self.widget_6 = QtWidgets.QWidget(Form)
self.widget_6.setEnabled(True)
self.widget_6.setGeometry(QtCore.QRect(240, 250, 151, 68))
self.widget_6.setStyleSheet("background-color: rgb(230, 230, 230);")
self.widget_6.setObjectName("widget_6")
self.verticalLayout_4 = QtWidgets.QVBoxLayout(self.widget_6)
self.verticalLayout_4.setContentsMargins(0, 0, 0, 0)
self.verticalLayout_4.setObjectName("verticalLayout_4")
self.start_btn = QtWidgets.QPushButton(self.widget_6)
self.start_btn.setStyleSheet("")
self.start_btn.setObjectName("start_btn")
self.verticalLayout_4.addWidget(self.start_btn)
self.end_btn = QtWidgets.QPushButton(self.widget_6)
self.end_btn.setStyleSheet("")
self.end_btn.setObjectName("end_btn")
self.verticalLayout_4.addWidget(self.end_btn)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.start_btn.setText(_translate("Form", "start"))
self.end_btn.setText(_translate("Form", "end"))
import sys
from PyQt5.Qt import QApplication, QWidget
class Sorter(QWidget, Ui_Form):
"""
demo
"""
def __init__(self, parent=None, *args, **kwargs):
"""
init
"""
super(Sorter, self).__init__(parent, *args, **kwargs)
self.setupUi(self)
if __name__ == "__main__":
app = QApplication(sys.argv)
myWin = Sorter()
myWin.show()
sys.exit(app.exec_())
Related
I am trying to add a second tab (containing a pie chart visualization) to my PyQt5 GUI, but I cannot figure out how to display it. This second tab is laid out in a separate class and my program has the following structure:
main.py
from PyQt5 import QtWidgets, QtCore
from gui import UiMainWindow
import sys
class Logic(QtWidgets.QMainWindow, UiMainWindow,):
def __init__(self):
super().__init__()
self.setupUi(self)
self.treeView = QtWidgets.QTreeView(self.tabwidget.main_tab)
self.treeView.setGeometry(QtCore.QRect(270, 90, 801, 571))
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
logic = Logic()
logic.show()
sys.exit(app.exec_())
gui.py
from PyQt5 import QtWidgets, QtCore
from main_tab import MainTab
class UiMainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("Invoice Manager")
MainWindow.resize(1120, 750)
MainWindow.setTabShape(QtWidgets.QTabWidget.Rounded)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.tabwidget = MainTab(self.centralwidget)
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
self.tabwidget.setCurrentIndex(0)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("Test", "Test"))
self.tabwidget.setTabText(
self.tabwidget.indexOf(self.tabwidget.main_tab),
_translate("MainWindow", "Main"))
self.tabwidget.setTabText(
self.tabwidget.indexOf(self.tabwidget.visual_tab),
_translate("MainWindow", "Tab_2"))
main_tab.py
from PyQt5 import QtCore, QtWidgets
from tab_2 import Tab2
class MainTab(QtWidgets.QTabWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setGeometry(QtCore.QRect(0, 0, 1120, 750))
self.main_tab = QtWidgets.QWidget()
self.addTab(self.main_tab, "")
self.visual_tab = Tab2()
self.addTab(self.visual_tab, "")
tab_2.py
from PyQt5 import QtWidgets
from PyQt5.QtChart import QChart, QChartView, QPieSeries, QPieSlice
from PyQt5.QtGui import QPainter, QPen
from PyQt5.QtCore import Qt
class Tab2(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.layout = QtWidgets.QVBoxLayout()
self.setLayout(self.layout)
self.create_piechart()
def create_piechart(self):
series = QPieSeries()
series.append("Label 1", 2)
series.append("Label 2", 2)
series.append("Label 3", 2)
pie_slice = QPieSlice()
pie_slice.setExploded(True)
pie_slice.setLabelVisible(True)
pie_slice.setPen(QPen(Qt.darkGreen, 2))
pie_slice.setBrush(Qt.green)
chart = QChart()
chart.legend().hide()
chart.addSeries(series)
chart.createDefaultAxes()
chart.setAnimationOptions(QChart.SeriesAnimations)
chart.setTitle("Pie Chart Example")
chart.legend().setVisible(True)
chart.legend().setAlignment(Qt.AlignBottom)
chartview = QChartView(chart)
chartview.setRenderHint(QPainter.Antialiasing)
I have been trying various solutions, but no luck so far. Any help would be highly appreciated!
How to let MouseEvent working?
I try to print mouse tracking to label x,y coordinate but always fail. I already using setMouseTracking(True), generate from QtDesigner ui to py.
code Below:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(640, 480)
Form.setMouseTracking(True)
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(270, 190, 58, 15))
self.label.setObjectName("label")
self.label.setMouseTracking(True)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.label.setText(_translate("Form", "TextLabel"))
def mouseMoveEvent(self, e):
x = e.x()
y = e.y()
text = "x: {0}, y: {1}".format(x, y)
self.label.setText(text)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
Form = QtWidgets.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
Ui_Form is not a widget, so it will not have the mouseMoveEvent method, as the PyQt docs point out you must create a class that inherits the appropriate widget, in this case QWidget, and use the interface provided by Qt Designer:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(640, 480)
Form.setMouseTracking(True)
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(270, 190, 58, 15))
self.label.setObjectName("label")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.label.setText(_translate("Form", "TextLabel"))
class Form(QtWidgets.QWidget, Ui_Form):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.setupUi(self)
self.setMouseTracking(True)
def mouseMoveEvent(self, e):
text = "x: {0}, y: {1}".format(e.x(), e.y())
self.label.setText(text)
self.label.adjustSize()
super(Form, self).mouseMoveEvent(e)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Form()
w.show()
sys.exit(app.exec_())
I'm writing a QtWidget that displays a QComboBox (drop down menu) using PyQt5. However, it's coming up empty. Does anyone know why?
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Test(QtWidgets.QWidget):
def __init__(self, formname = "Test"):
super().__init__()
self.formname = formname
self.impute_methods = ["Method 1", "Method 2"]
def setupUi(self, Form):
Form.setObjectName(self.formname)
Form.resize(1154, 902)
self._create_buttons(Form)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def _create_buttons(self, Form):
self.test_box = QtWidgets.QComboBox()
self.test_box.addItems(self.impute_methods)
self.test_box.setGeometry(QtCore.QRect(110, 190, 150, 27))
self.test_box.setObjectName("test_box")
def selectionchange(self, i):
print(i)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate(self.formname, "Test"))
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
tester = QtWidgets.QDialog()
ui = Test()
ui.setupUi(tester)
tester.show()
sys.exit(app.exec_())
Here is a screenshot of what I see:
set parent for comboBox to place it on Test():
def _create_buttons(self, Form):
self.test_box = QtWidgets.QComboBox(self)
...
and for ui to place it on the dialog:
...
ui = Test()
ui.setParent(tester)
...
I am using a PyQt4.QMainWindow as my application interface, and I want to get the x and y coordinates of the mouse inside of a QWidget and set them continuously in 2 textBrowsers in the MainWindow.
The documentation for QWidget is here.
and the documentation for QMouseEvent is here.
Here is the code
from PyQt4 import QtGui
from PyQt4.QtGui import QApplication
import sys
class Ui_MainWindow(object):
def setupUI(self, MainWindow):
self.textBrowser_1 = QtGui.QTextBrowser(self.tab)
self.textBrowser_2 = QtGui.QTextBrowser(self.tab)
self.widget_1 = QtGui.QWidget(self.tab)
self.widget_1.setMouseTracking(True)
class MyMainScreen(QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.ui = Ui_MainWindow() # This is from a python export from QtDesigner
# There is a QWidget inside that is self.ui.widget_1
# and 2 textBrowsers, textBrowser_1 and textBrowser_2
# I want to populate these 2 textBrowsers with the current x,y
# coordinates.
if __name__ == "__main__":
app = QApplication(sys.argv)
mainscreen = MyMainScreen()
mainscreen.show()
app.exec_()
When you apply setMouseTracking it only applies to that widget, and not to your children, so you must manually, in the next solution:
def setMouseTracking(self, flag):
def recursive_set(parent):
for child in parent.findChildren(QtCore.QWidget):
child.setMouseTracking(flag)
recursive_set(child)
QtGui.QWidget.setMouseTracking(self, flag)
recursive_set(self)
complete code:
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyQt4.QtGui import QApplication, QMainWindow
import sys
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.resize(800, 132)
self.centralwidget = QtGui.QWidget(MainWindow)
self.horizontalLayout = QtGui.QHBoxLayout(self.centralwidget)
self.textBrowser_1 = QtGui.QTextBrowser(self.centralwidget)
self.horizontalLayout.addWidget(self.textBrowser_1)
self.textBrowser_2 = QtGui.QTextBrowser(self.centralwidget)
self.horizontalLayout.addWidget(self.textBrowser_2)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
MainWindow.setStatusBar(self.statusbar)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
class MyMainScreen(QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.ui = Ui_MainWindow() # This is from a python export from QtDesigner
self.ui.setupUi(self)
self.setMouseTracking(True)
self.ui.textBrowser_1.setMouseTracking(True)
self.ui.textBrowser_2.setMouseTracking(True)
self.ui.menubar.setMouseTracking(True)
self.ui.statusbar.setMouseTracking(True)
def setMouseTracking(self, flag):
def recursive_set(parent):
for child in parent.findChildren(QtCore.QWidget):
child.setMouseTracking(flag)
recursive_set(child)
QtGui.QWidget.setMouseTracking(self, flag)
recursive_set(self)
def mouseMoveEvent(self, event):
pos = event.pos()
self.ui.textBrowser_1.append(str(pos.x()))
self.ui.textBrowser_2.append(str(pos.y()))
QtGui.QMainWindow.mouseMoveEvent(self, event)
if __name__ == "__main__":
app = QApplication(sys.argv)
mainscreen = MyMainScreen()
mainscreen.show()
app.exec_()
This is my output:
I want to write a simple program shows a picture and print which pixel was clicked by override mousePressEvent of QGraphicsView.
When I don't override mousePressEvent of QGraphicsView, the image shows fine. But when I do override it, not only the position failed to show itself, the canvas become blank.
before override:
import sys
from PyQt5 import Qt
from PyQt5 import uic
a = Qt.QApplication(sys.argv)
from untitled import Ui_Form
# class override_graphicsView (Qt.QGraphicsView):
#
# def mousePressEvent(self, event):
# print(event.pos())
class Image_Process(Qt.QWidget):
def __init__(self):
super(Image_Process, self).__init__()
self.path = r"d:\test\winxp.jpg" #image path
self.new = Ui_Form()
self.new.setupUi(self)
# self.new.graphicsView = override_graphicsView()
self.pixmap = Qt.QPixmap()
self.pixmap.load(self.path)
self.pixmap = self.pixmap.scaled(self.size(), Qt.Qt.KeepAspectRatio)
self.graphicsPixmapItem = Qt.QGraphicsPixmapItem(self.pixmap)
self.graphicsScene = Qt.QGraphicsScene()
self.graphicsScene.addItem(self.graphicsPixmapItem)
self.new.graphicsView.setScene(self.graphicsScene)
my_Qt_Program = Image_Process()
my_Qt_Program.show()
sys.exit(a.exec_())
After I uncomment those lines, the canvas becomes this, and nothing was printed after click.
The untitled.py was generated from QtDesigner
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created: Mon Jan 12 02:07:05 2015
# by: PyQt5 UI code generator 5.3.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(451, 286)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(Form.sizePolicy().hasHeightForWidth())
Form.setSizePolicy(sizePolicy)
self.gridLayout = QtWidgets.QGridLayout(Form)
self.gridLayout.setObjectName("gridLayout")
self.graphicsView = QtWidgets.QGraphicsView(Form)
self.graphicsView.setObjectName("graphicsView")
self.gridLayout.addWidget(self.graphicsView, 0, 0, 1, 1)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
Helped by Plouff, I have solved my own problem.
First, I should override QGraphicsScene instead of QGraphicsView, and the following line should be called for QGraphicsScene to handle mousePressEvent
super(override_graphicsScene, self).mousePressEvent(event)
Modified code:
import sys
from PyQt5 import Qt
from PyQt5 import uic
a = Qt.QApplication(sys.argv)
from untitled import Ui_Form
# Override like this:
class override_graphicsScene (Qt.QGraphicsScene):
def __init__(self,parent = None):
super(override_graphicsScene,self).__init__(parent)
def mousePressEvent(self, event):
super(override_graphicsScene, self).mousePressEvent(event)
print(event.pos())
class Image_Process(Qt.QWidget):
def __init__(self):
super(Image_Process, self).__init__()
self.path = r"d:\test\winxp.jpg" #image path
self.new = Ui_Form()
self.new.setupUi(self)
self.pixmap = Qt.QPixmap()
self.pixmap.load(self.path)
self.pixmap = self.pixmap.scaled(self.size(), Qt.Qt.KeepAspectRatio)
self.graphicsPixmapItem = Qt.QGraphicsPixmapItem(self.pixmap)
self.graphicsScene = override_graphicsScene(self)
self.graphicsScene.addItem(self.graphicsPixmapItem)
self.new.graphicsView.setScene(self.graphicsScene)
my_Qt_Program = Image_Process()
my_Qt_Program.show()
sys.exit(a.exec_())
The program works fine.