just like the title says i'm trying to draw inside an existing QGraphicsView. The window I generated using QT Designer, and I would like to draw a matrix of 16x16 squares inside the QGraphicsView.
This is the code I have as of right now:
Window:
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.8.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(911, 567)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(20, 10, 301, 31))
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setObjectName("label")
self.groupBox = QtWidgets.QGroupBox(self.centralwidget)
self.groupBox.setGeometry(QtCore.QRect(620, 40, 271, 91))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.groupBox.setFont(font)
self.groupBox.setObjectName("groupBox")
self.rdtest = QtWidgets.QRadioButton(self.groupBox)
self.rdtest.setGeometry(QtCore.QRect(60, 60, 101, 22))
self.rdtest.setObjectName("rdtest")
self.rdtrain = QtWidgets.QRadioButton(self.groupBox)
self.rdtrain.setGeometry(QtCore.QRect(60, 30, 101, 22))
self.rdtrain.setObjectName("rdtrain")
self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)
self.graphicsView.setGeometry(QtCore.QRect(10, 40, 601, 411))
self.graphicsView.setObjectName("graphicsView")
self.clear = QtWidgets.QPushButton(self.centralwidget)
self.clear.setGeometry(QtCore.QRect(10, 470, 88, 29))
self.clear.setObjectName("clear")
self.trainNewInput = QtWidgets.QPushButton(self.centralwidget)
self.trainNewInput.setGeometry(QtCore.QRect(500, 470, 111, 29))
self.trainNewInput.setObjectName("trainNewInput")
self.trainbox = QtWidgets.QGroupBox(self.centralwidget)
self.trainbox.setGeometry(QtCore.QRect(620, 150, 271, 171))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.trainbox.setFont(font)
self.trainbox.setObjectName("trainbox")
self.vtrain = QtWidgets.QLineEdit(self.trainbox)
self.vtrain.setGeometry(QtCore.QRect(100, 70, 101, 29))
self.vtrain.setObjectName("vtrain")
self.label_2 = QtWidgets.QLabel(self.trainbox)
self.label_2.setGeometry(QtCore.QRect(40, 70, 56, 31))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.trainDefault = QtWidgets.QPushButton(self.trainbox)
self.trainDefault.setGeometry(QtCore.QRect(40, 30, 161, 29))
self.trainDefault.setObjectName("trainDefault")
self.output = QtWidgets.QLabel(self.trainbox)
self.output.setGeometry(QtCore.QRect(10, 130, 271, 17))
self.output.setText("")
self.output.setObjectName("output")
self.output_2 = QtWidgets.QLabel(self.trainbox)
self.output_2.setGeometry(QtCore.QRect(10, 150, 271, 17))
self.output_2.setText("")
self.output_2.setObjectName("output_2")
self.testbox = QtWidgets.QGroupBox(self.centralwidget)
self.testbox.setGeometry(QtCore.QRect(620, 330, 271, 171))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.testbox.setFont(font)
self.testbox.setObjectName("testbox")
self.pushButton = QtWidgets.QPushButton(self.testbox)
self.pushButton.setGeometry(QtCore.QRect(50, 40, 161, 29))
self.pushButton.setObjectName("pushButton")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 911, 23))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "RNA: Numeros "))
self.groupBox.setTitle(_translate("MainWindow", "Opciones:"))
self.rdtest.setText(_translate("MainWindow", "Test"))
self.rdtrain.setText(_translate("MainWindow", "Train"))
self.clear.setText(_translate("MainWindow", "Clear"))
self.trainNewInput.setText(_translate("MainWindow", "Train new Input"))
self.trainbox.setTitle(_translate("MainWindow", "Train:"))
self.label_2.setText(_translate("MainWindow", "% Test:"))
self.trainDefault.setText(_translate("MainWindow", "Train Default Data"))
self.testbox.setTitle(_translate("MainWindow", "Test:"))
self.pushButton.setText(_translate("MainWindow", "Start Test"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Logic class where I want to create a method that draws on the QGraphicsView from the window:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QGraphicsScene
from PyQt5.QtCore import (QLineF, QPointF, QRectF, Qt)
from PyQt5.QtWidgets import QWidget, QApplication
from PyQt5.QtWidgets import (QApplication, QGraphicsView, QGraphicsScene, QGraphicsItem,
QGridLayout, QVBoxLayout, QHBoxLayout,
QLabel, QLineEdit, QPushButton)
from window import Ui_MainWindow
from RNA import NumberIA
train = []
train_r = []
test = []
test_r = []
class MyFirstGuiProgram(Ui_MainWindow):
def __init__(self, dialog):
Ui_MainWindow.__init__(self)
self.setupUi(dialog)
self.rdtrain.setChecked(True)
# Connect "add" button with a custom function (addInputTextToListbox)
self.clear.clicked.connect(self.addInputTextToListbox)
self.trainDefault.clicked.connect(self.t_DefaultData)
self.rdtest.clicked.connect(self.enableTest)
self.rdtrain.clicked.connect(self.enableTrain)
def enableTest(self):
self.trainbox.setEnabled(False)
self.trainNewInput.setEnabled(False)
self.testbox.setEnabled(True)
def drawSomething(self):
tes = "f"
def enableTrain(self):
self.trainbox.setEnabled(True)
self.trainNewInput.setEnabled(True)
self.testbox.setEnabled(False)
def addInputTextToListbox(self):
print("Hello world!!!")
def t_DefaultData(self):
ann = NumberIA()
t = self.vtrain.text()
print("Training data: ", t)
global train
global train_r
global test
global test_r
train, train_r, test, test_r = ann.read_file(float(t))
self.output.setText("Train complete...")
ann.crear_red(train, train_r)
accuracy, matrix = ann.probar_red(test, test_r)
self.output_2.setText("Accuracy: " + str(accuracy * 100) + "%")
print("Matris de Confusion:")
print('\n'.join([''.join(['{:4}'.format(item) for item in row])
for row in matrix]))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = MyFirstGuiProgram(MainWindow)
MainWindow.show()
MainWindow.setWindowTitle("RNA: Inteligencia Artificial 2")
ui.enableTrain()
sys.exit(app.exec_())
I cant seem to find examples on how to to this online, the examples I have found are vague to me and cant seem to figure it out.
I recommend you inherit from QMainWindow and implement the Ui_MainWindow interface, to draw in a QGraphicsView you must use a QGraphicsScene, and use its methods, in this case use addRect().
from PyQt5 import QtCore, QtGui, QtWidgets
class MyFirstGuiProgram(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent=parent)
self.setupUi(self)
scene = QtWidgets.QGraphicsScene()
self.graphicsView.setScene(scene)
pen = QtGui.QPen(QtCore.Qt.green)
side = 20
for i in range(16):
for j in range(16):
r = QtCore.QRectF(QtCore.QPointF(i*side, j*side), QtCore.QSizeF(side, side))
scene.addRect(r, pen)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MyFirstGuiProgram()
w.show()
sys.exit(app.exec_())
You can also draw it by QLineF(), it gives more control from design point of view.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def sceneWithPen(grid):
scene = QGraphicsScene()
view = QGraphicsView()
view.setScene(scene)
# Creating line's colors
red = QColor(qRgb(172, 50, 99))
blue = QColor(qRgb(50, 150, 203))
# Set length of square's side and number of horizontal and vertical lines
vLines = 16
hLines = 16
side = 30
# Set starting values for loops
hor = 0
ver = 0
subdiv = 16
leftX,leftY = 0, 0
rightX, rightY = subdiv*side, 0
bottomX, bottomY= 0, 0
topX, topY = 0, subdiv*side
while ver < vLines:
# Drawing vertical lines
ver = ver + 1
vLine = QLineF(bottomX, bottomY, topX, topY)
bottomX, topX = bottomX + side, topX + side
scene.addLine(vLine, red)
while hor < hLines:
#Drawing horizontal lines
hor = hor + 1
hLine = QLineF(leftX, leftY, rightX, rightY)
leftY, rightY = leftY + side, rightY + side
scene.addLine(hLine, blue)
grid.addWidget(view)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = QWidget()
grid = QGridLayout()
sceneWithPen(grid)
w.setLayout(grid)
w.show()
sys.exit(app.exec_())
It will be like this:
Great example #eyllanesc just gave you right above, here is another small example I just happened to have laying around, if you need to draw like a simple free hand.
Have your MainWindow, for example a QMainWindow or Qwidget or...
Have a QGraphicsView.
Set the QGraphicsView's scene with your QGraphicsScene
Have your own QGraphicsPathItem so you can set properties you need.
Have the implementation of what you want to draw inside your scene, so it knows how to draw on itself.
Having things in this way you will have control of several scenes knowing how to draw on itself independently, of course if you will need more than one scene.
This example the logic were implemented inside the QGraphicsView, you could move it to your GraphicsScene.
class MainWindow(QMainWindow):
central_widget = None
layout_container = None
def __init__(self):
super(MainWindow, self).__init__()
self.central_widget = QWidget()
self.layout_container = QVBoxLayout()
self.central_widget.setLayout(self.layout_container)
self.setCentralWidget(self.central_widget)
self.layout_container.addWidget(GraphicsView())
class GraphicsView(QGraphicsView):
start = None
end = None
item = None
path = None
def __init__(self):
super(GraphicsView, self).__init__()
self.setScene(QGraphicsScene())
self.path = QPainterPath()
self.item = GraphicsPathItem()
self.scene().addItem(self.item)
def mousePressEvent(self, event):
self.start = self.mapToScene(event.pos())
self.path.moveTo(self.start)
def mouseMoveEvent(self, event):
self.end = self.mapToScene(event.pos())
self.path.lineTo(self.end)
self.start = self.end
self.item.setPath(self.path)
class GraphicsPathItem(QGraphicsPathItem):
def __init__(self):
super(GraphicsPathItem, self).__init__()
pen = QPen()
pen.setColor(Qt.black)
pen.setWidth(10)
self.setPen(pen)
if __name__ == '__main__':
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
Related
I have a QGraphicsView with a QGraphicsScene. On QGraphicsScene, I output the image using QGraphicsPixmapItem. And I would like to draw an ellipse over the image with my mouse.
I have that code now. And the ellipse is drawn on MainWindow.
What do I need to do to have the ellipse drawn on an image in QGraphicsView?
Code OFT_MainWindow
# OFT_MainWindow
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(862, 710)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.graphicsView = QtWidgets.QGraphicsView(self.centralwidget)
self.graphicsView.setGeometry(QtCore.QRect(10, 90, 841, 571))
self.graphicsView.setMouseTracking(True)
self.graphicsView.setObjectName("graphicsView")
self.buttonBox = QtWidgets.QDialogButtonBox(self.centralwidget)
self.buttonBox.setGeometry(QtCore.QRect(360, 670, 81, 31))
font = QtGui.QFont()
font.setPointSize(10)
self.buttonBox.setFont(font)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(760, 10, 91, 31))
font = QtGui.QFont()
font.setPointSize(10)
self.pushButton.setFont(font)
self.pushButton.setObjectName("pushButton")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(10, 10, 731, 31))
self.lineEdit.setObjectName("lineEdit")
self.lineEdit_2 = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit_2.setGeometry(QtCore.QRect(10, 670, 331, 31))
self.lineEdit_2.setObjectName("lineEdit_2")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(10, 50, 841, 31))
font = QtGui.QFont()
font.setPointSize(10)
self.pushButton_2.setFont(font)
self.pushButton_2.setObjectName("pushButton_2")
MainWindow.setCentralWidget(self.centralwidget)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "Browse"))
self.pushButton_2.setText(_translate("MainWindow", "Highlight field area"))
Main code
import OFT_MainWindow
import sys
import os
import numpy as np
import cv2
from PIL import Image, ImageQt, ImageEnhance
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import QtCore
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.Qt import Qt
def main():
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
class MainWindow(QtWidgets.QMainWindow, OFT_MainWindow.Ui_MainWindow, QtWidgets.QGraphicsView, QtWidgets.QGraphicsScene):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.browse_file)
self.pushButton_2.clicked.connect(self.imageFrame)
self.begin = QtCore.QPoint()
self.end = QtCore.QPoint()
self.show()
###################################################################################
def browse_file(self):
self.lineEdit.clear()
file = QtWidgets.QFileDialog.getOpenFileName(self, "Choose file")
file = str(file[0])
if file:
self.lineEdit.setText(file) # добавить путь в lineEdit
# cap = cv2.VideoCapture(file)
###################################################################################
def imageFrame(self):
file = self.lineEdit.text()
self.drawing = False
self.lastPoint = QPoint()
scene = QtWidgets.QGraphicsScene(self)
self.image = QPixmap(file)
item = QtWidgets.QGraphicsPixmapItem(self.image)
scene.addItem(item)
view = self.graphicsView.setScene(scene)
# self.show()
def paintEvent(self, event):
qp = QtGui.QPainter(self)
br = QtGui.QBrush(QtGui.QColor(0, 255, 0, 25))
qp.setBrush(br)
ellipse = qp.drawEllipse(QtCore.QRect(self.begin, self.end))
coord_a = self.begin
coord_a = str(coord_a)
coord_a = coord_a[20:][:-1]
coord_b = self.end
coord_b = str(coord_b)
coord_b = coord_b[20:][:-1]
coord = ('begin = ' + coord_a + ' end = ' + coord_b)
self.lineEdit_2.setText(coord)
def mousePressEvent(self, event):
self.begin = event.pos()
self.end = event.pos()
self.update()
def mouseMoveEvent(self, event):
self.end = event.pos()
self.update()
###################################################################################
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.aboutToQuit.connect(app.deleteLater)
sys.exit(app.exec_())
If you want to paint something on a QGraphicsView, you have to add QGraphicsItem to its scene, otherwise you're making almost useless to crete a QGraphicsView to begin with.
One possible solution is to install an event filter on the scene, listen for mouse button events and draw an ellipse (using QGraphicsEllipseItem) on the scene if the first click is done within the contents of a QGraphicsPixmapItem.
Note that another possibility is to subclass from QGraphicsPixmapItem and implement its mouse events instead. It all depends on what you're going to do and what you're going to need from your program.
class MainWindow(QtWidgets.QMainWindow, OFT_MainWindow.Ui_MainWindow):
def __init__(self, parent=None):
super().__init__(parent)
# ...
self.ellipseItem = None
def imageFrame(self):
# ...
scene.installEventFilter(self)
def eventFilter(self, source, event):
if event.type() == QtCore.QEvent.GraphicsSceneMousePress:
for item in self.graphicsView.scene().items(event.scenePos()):
if isinstance(item, QtWidgets.QGraphicsPixmapItem):
self.reference = item
self.ellipseItem = QtWidgets.QGraphicsEllipseItem(item)
self.ellipseItem.setBrush(QtGui.QColor(0, 255, 0, 25))
self.start = item.mapFromScene(event.scenePos())
elif event.type() == QtCore.QEvent.GraphicsSceneMouseMove and self.ellipseItem:
end = self.reference.mapFromScene(event.scenePos())
self.ellipseItem.setRect(QtCore.QRectF(self.start, end))
elif event.type() == QtCore.QEvent.GraphicsSceneMouseRelease and self.ellipseItem:
self.ellipseItem = None
return super().eventFilter(source, event)
Note that subclassing your Main window from all those classes (QtWidgets.QMainWindow, OFT_MainWindow.Ui_MainWindow, QtWidgets.QGraphicsView, QtWidgets.QGraphicsScene) is not only unnecessary and meaningless, but absolutely WRONG: multiple-inheritance subclassing should only be done when you know what you're inheriting from and why, otherwise, just don't. For Qt widgets that load from UI files, just subclass from the base widget class and the Ui.
I want to add one functionality in my application when update is done then data in pyqt5 table should automatically refreshed with the new data in search results. But when I click the buttom, there is nothing happened.
# -*- coding: utf-8 -*-
from PyQt5 import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
import logging
import logging.config
import time
class Ui_Control_system(object):
def setupUi(self, Control_system):
Control_system.setObjectName("Control_system")
Control_system.resize(1004, 722)
Control_system.setFixedSize(1004, 722)
Control_system.setWindowIcon(QIcon('images/icon.png'))
Control_system.setStyleSheet("QMainWindow{border-image:url(images/background.jpg)}")
self.centralwidget = QtWidgets.QWidget(Control_system)
self.centralwidget.setObjectName("centralwidget")
#表格显示
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(130, 170, 752, 245))
self.tableWidget.setRowCount(8)
self.tableWidget.setColumnCount(6)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.horizontalHeader().setVisible(False)
self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
self.tableWidget.horizontalHeader().setDefaultSectionSize(125)
self.tableWidget.horizontalHeader().setHighlightSections(True)
self.tableWidget.horizontalHeader().setSortIndicatorShown(False)
self.tableWidget.verticalHeader().setVisible(False)
Control_system.setCentralWidget(self.centralwidget)
self.tableWidget.setAutoFillBackground(True)
self.tableWidget.setItem(0,0,QTableWidgetItem("机器编号"))
self.tableWidget.setItem(0,1,QTableWidgetItem("烟雾值"))
self.tableWidget.setItem(0,2,QTableWidgetItem("火焰值"))
self.tableWidget.setItem(0,3, QTableWidgetItem("温度值"))
self.tableWidget.setItem(0,4, QTableWidgetItem("电流值"))
self.tableWidget.setItem(0,5, QTableWidgetItem("电压值"))
font = QtGui.QFont()
font.setPointSize(15)
font.setBold(True)
self.tableWidget.item(0,0).setFont(font)
self.tableWidget.item(0,1).setFont(font)
self.tableWidget.item(0,2).setFont(font)
self.tableWidget.item(0,3).setFont(font)
self.tableWidget.item(0,4).setFont(font)
self.tableWidget.item(0,5).setFont(font)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(360, 70, 300, 50))
self.label.setObjectName("label")
self.label.setAutoFillBackground(True)
self.label.setAlignment(Qt.AlignCenter)
self.label.setStyleSheet("border-image:url(images/title.png)")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(730, 480, 121, 41))
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.slotStart)
Control_system.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(Control_system)
self.statusbar.setObjectName("statusbar")
Control_system.setStatusBar(self.statusbar)
self.retranslateUi(Control_system)
QtCore.QMetaObject.connectSlotsByName(Control_system)
def retranslateUi(self, Control_system):
_translate = QtCore.QCoreApplication.translate
Control_system.setWindowTitle(_translate("Control_system", "实时监控系统"))
self.pushButton.setText(_translate("Control_system", "开始运行"))
def slotStart(self):
#开始按钮不可点击,线程开始
self.pushButton.setEnabled(False)
self.update_data_thread = UpdateData()
self.update_data_thread.update_data.connect(self.set_btn)
self.update_data_thread.start()
def set_btn(self):
self.pushButton.setEnabled(True)
class UpdateData(QtCore.QThread):#使用qt自己本身的线程
update_data=QtCore.pyqtSignal()#因为这个信号槽要继承于Qobject,不然会发生没有emit,connect函数的报错,括号里面填写的是发射的数据类型
#print(".............")
def __init__(self):
super().__init__()
def run(self):
cnt = 0
while True:
cnt += 1
self.tableWidget.setItem(2,2,QTableWidgetItem(cnt))
self.update_data.emit() # 发射信号
time.sleep(1)
if __name__ == '__main__':
if not QtWidgets.QApplication.instance():
app = QtWidgets.QApplication(sys.argv)
else:
app = QtWidgets.QApplication.instance()
MainWindow = QtWidgets.QMainWindow()
ui = Ui_Control_system()
ui.setupUi(MainWindow) # 将ui实例绘制到窗口实例上
desktop = QtWidgets.QApplication.desktop()
x = (desktop.width() - MainWindow.width()) // 2
y = (desktop.height() - MainWindow.height()) // 2
MainWindow.move(x,y)
MainWindow.show()
sys.exit(app.exec())#exec_()方法的作用是“进入程序的主循环直到exit()被调
You cannot and should not modify the GUI directly from another thread, in your case QTableWidget and QTableWidgetItem are part of the GUI so the code: self.tableWidget.setItem(2, 2, QTableWidgetItem(cnt)) is incorrect. What should be done is to send the information to the main thread through elements that are thread-safe such as signals, QEvents, etc.
On the other hand PyQt recommends not modifying the class it generates but creating a widget and using the generated class as an interface(1).
Considering the above the solution is:
import sys
import time
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Control_system(object):
def setupUi(self, Control_system):
Control_system.setObjectName("Control_system")
Control_system.resize(1004, 722)
Control_system.setFixedSize(1004, 722)
Control_system.setWindowIcon(QtGui.QIcon("images/icon.png"))
Control_system.setStyleSheet(
"QMainWindow{border-image:url(images/background.jpg)}"
)
self.centralwidget = QtWidgets.QWidget(Control_system)
self.centralwidget.setObjectName("centralwidget")
# 表格显示
self.tableWidget = QtWidgets.QTableWidget(self.centralwidget)
self.tableWidget.setGeometry(QtCore.QRect(130, 170, 752, 245))
self.tableWidget.setRowCount(8)
self.tableWidget.setColumnCount(6)
self.tableWidget.setObjectName("tableWidget")
self.tableWidget.horizontalHeader().setVisible(False)
self.tableWidget.horizontalHeader().setCascadingSectionResizes(False)
self.tableWidget.horizontalHeader().setDefaultSectionSize(125)
self.tableWidget.horizontalHeader().setHighlightSections(True)
self.tableWidget.horizontalHeader().setSortIndicatorShown(False)
self.tableWidget.verticalHeader().setVisible(False)
Control_system.setCentralWidget(self.centralwidget)
self.tableWidget.setAutoFillBackground(True)
self.tableWidget.setItem(0, 0, QtWidgets.QTableWidgetItem("机器编号"))
self.tableWidget.setItem(0, 1, QtWidgets.QTableWidgetItem("烟雾值"))
self.tableWidget.setItem(0, 2, QtWidgets.QTableWidgetItem("火焰值"))
self.tableWidget.setItem(0, 3, QtWidgets.QTableWidgetItem("温度值"))
self.tableWidget.setItem(0, 4, QtWidgets.QTableWidgetItem("电流值"))
self.tableWidget.setItem(0, 5, QtWidgets.QTableWidgetItem("电压值"))
font = QtGui.QFont()
font.setPointSize(15)
font.setBold(True)
self.tableWidget.item(0, 0).setFont(font)
self.tableWidget.item(0, 1).setFont(font)
self.tableWidget.item(0, 2).setFont(font)
self.tableWidget.item(0, 3).setFont(font)
self.tableWidget.item(0, 4).setFont(font)
self.tableWidget.item(0, 5).setFont(font)
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(360, 70, 300, 50))
self.label.setObjectName("label")
self.label.setAutoFillBackground(True)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setStyleSheet("border-image:url(images/title.png)")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(730, 480, 121, 41))
self.pushButton.setObjectName("pushButton")
Control_system.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(Control_system)
self.statusbar.setObjectName("statusbar")
Control_system.setStatusBar(self.statusbar)
self.retranslateUi(Control_system)
QtCore.QMetaObject.connectSlotsByName(Control_system)
def retranslateUi(self, Control_system):
_translate = QtCore.QCoreApplication.translate
Control_system.setWindowTitle(_translate("Control_system", "实时监控系统"))
self.pushButton.setText(_translate("Control_system", "开始运行"))
class Control_system(QtWidgets.QMainWindow, Ui_Control_system):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.slotStart)
#QtCore.pyqtSlot()
def slotStart(self):
self.pushButton.setEnabled(False)
self.update_data_thread = UpdateData(self)
self.update_data_thread.dataChanged.connect(self.onDataChanged)
self.update_data_thread.start()
#QtCore.pyqtSlot(int, int, str)
def onDataChanged(self, row, column, text):
it = self.tableWidget.item(row, column)
if it is None:
it = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(row, column, it)
it.setText(text)
class UpdateData(QtCore.QThread):
dataChanged = QtCore.pyqtSignal(int, int, str)
def run(self):
cnt = 0
while True:
cnt += 1
self.dataChanged.emit(2, 2, str(cnt))
time.sleep(1)
if __name__ == "__main__":
app = QtWidgets.QApplication.instance()
if app is None:
app = QtWidgets.QApplication(sys.argv)
w = Control_system()
w.show()
sys.exit(app.exec_())
Update:
class Control_system(QtWidgets.QMainWindow, Ui_Control_system):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.pushButton.clicked.connect(self.slotStart)
self.pushButton_2.clicked.connect(self.slotStop)
#QtCore.pyqtSlot()
def slotStart(self):
# ...
#QtCore.pyqtSlot(int, int, str)
def onDataChanged(self, row, column, text):
it = self.tableWidget.item(row, column)
if it is None:
it = QtWidgets.QTableWidgetItem()
self.tableWidget.setItem(row, column, it)
it.setText(text)
#QtCore.pyqtSlot()
def slotStop(self):
self.update_data_thread.requestInterruption()
self.update_data_thread.quit()
self.update_data_thread.wait()
self.pushButton.setEnabled(True)
class UpdateData(QtCore.QThread):
dataChanged = QtCore.pyqtSignal(int, int, str)
def run(self):
cnt = 0
while not self.isInterruptionRequested(): # <---
cnt += 1
self.dataChanged.emit(2, 2, str(cnt))
time.sleep(1)
(1) Using the Generated Code
So I just started working with PyQt5. Right now I only programmed 1 button that's supposed to take text from a line edit, store it in a global variable and put it in a text browser. Now it does this... but with issues.
The text browser does NOT update until I click another program/window and then click my app again
When the line edit is cleared there is a bug which is basically text not being cleared properly but only it's top half. This goes away when I type again.
I tried calling the .update() methods for the widgets and QApplication.process_events()
Here's the code
from PyQt5 import QtCore, QtGui, QtWidgets
lyrics = ''
adlib = ' (Placeholder adlib)'
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(742, 680)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.addLineBtn = QtWidgets.QPushButton(self.centralwidget)
self.addLineBtn.setGeometry(QtCore.QRect(530, 0, 91, 51))
font = QtGui.QFont()
font.setFamily("Arial")
font.setItalic(True)
self.addLineBtn.setFont(font)
self.addLineBtn.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.addLineBtn.setObjectName("addLineBtn")
self.deleteBtn = QtWidgets.QPushButton(self.centralwidget)
self.deleteBtn.setGeometry(QtCore.QRect(120, 80, 91, 32))
self.deleteBtn.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.deleteBtn.setObjectName("deleteBtn")
self.saveBtn = QtWidgets.QPushButton(self.centralwidget)
self.saveBtn.setGeometry(QtCore.QRect(30, 80, 91, 32))
self.saveBtn.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.saveBtn.setObjectName("saveBtn")
self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)
self.lineEdit.setGeometry(QtCore.QRect(30, 20, 501, 51))
self.lineEdit.setObjectName("lineEdit")
self.dialLabel = QtWidgets.QLabel(self.centralwidget)
self.dialLabel.setGeometry(QtCore.QRect(640, 20, 71, 16))
self.dialLabel.setObjectName("dialLabel")
self.rtdSlider = QtWidgets.QSlider(self.centralwidget)
self.rtdSlider.setGeometry(QtCore.QRect(620, 40, 101, 22))
self.rtdSlider.setOrientation(QtCore.Qt.Horizontal)
self.rtdSlider.setObjectName("rtdSlider")
self.textBrowser = QtWidgets.QTextBrowser(self.centralwidget)
self.textBrowser.setGeometry(QtCore.QRect(20, 120, 701, 501))
self.textBrowser.setObjectName("textBrowser")
self.noadlibBtn = QtWidgets.QPushButton(self.centralwidget)
self.noadlibBtn.setGeometry(QtCore.QRect(530, 50, 91, 51))
font = QtGui.QFont()
font.setFamily("Arial")
font.setItalic(True)
self.noadlibBtn.setFont(font)
self.noadlibBtn.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
self.noadlibBtn.setObjectName("noadlibBtn")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 742, 22))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.addLineBtn.clicked.connect(self.addLineAdlib)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.addLineBtn.setText(_translate("MainWindow", "Adlib"))
self.deleteBtn.setText(_translate("MainWindow", "Delete"))
self.saveBtn.setText(_translate("MainWindow", "Save"))
self.dialLabel.setText(_translate("MainWindow", "RTD Level"))
self.noadlibBtn.setText(_translate("MainWindow", "No Adlib"))
def addLineAdlib(self):
global lyrics
lyrics += self.lineEdit.text() + adlib + '\n'
self.lineEdit.clear()
self.textBrowser.setText(lyrics)
def addLineNoAdlib(self):
pass
def save(self):
pass
def deleteLine(self):
pass
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
I found the same problem as yours and I use MacOS Mojave 10.14.6. This problem maybe due to OS, but I downgraded pyqt5 from the latest 5.14.1 to a stable version 5.9.2, the problem was solved.
This problem also happens with macos 10.15.6 + pyqt 5.15.0.
I created a small example with qtdesigner (with 1 lineEdit box, 1 label box, 1 button), and then created python file with pyuic5 as well as with pyside2-uic.
Both the generated python files have the same problem - when "click" is pressed I have to move out of the window and back again to see the results. But if I just press enter after the input text then it shows up immediately.
The problem is solved by adding an extra line in the main class, for repainting the GUI, as shown below:
import sys
from PyQt5.QtWidgets import QDialog, QApplication
from demo_ui_pyuic5 import *
class MyForm(QDialog):
def __init__(self):
super().__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.ui.buttonClick.clicked.connect(self.dispmessage)
self.show()
def dispmessage(self):
self.ui.labelResponse.setText("Hello " + self.ui.lineEditName.text())
self.ui.labelResponse.repaint() # this line added to fix the problem
if __name__=="__main__":
app = QApplication(sys.argv)
w = MyForm()
w.show()
sys.exit(app.exec_())
1. The text browser does NOT update until I click another program/window and then click my app again - this issue can be related with your OS. I have got incorrect PyQT5 behavior on Ubuntu 16.04 while on Ubuntu 18.04 everything was working fine. Can you share more info?
Note: I tested your script on Ubuntu 18.04, I didn't need to click another program/window to refresh it
2. When the line edit is cleared there is a bug which is basically text not being cleared properly but only it's top half. This goes away when I type again. - Can you explain what do you mean by it's top half? If you meant that there is still (Placeholder adlib) text, you should modify your function to check lineEdit textbox before adding something to lyrics variable. For example, like this:
def addLineAdlib(self):
if self.lineEdit.text():
global lyrics
lyrics += self.lineEdit.text() + adlib + '\n'
self.lineEdit.clear()
self.textBrowser.setText(lyrics)
Here is a cleaner more class-ified (more pythonic pyqt) version of your program I have left commented out stuff in for you to see where it would have been but I removed your coordinate system and replaced it with the more standard Layout style of creating a GUI.
I tested this using python 3.7 pyqt5 on win10 so if there is OS issue you will know it but my guess (without digging into that ugly mess) is that there was a disconnection some where which created the issue you were experiencing.
Also your button as designed will never create a blank line since its always putting something on a line -- I tested this by just clicking the button without entering anything
from sys import exit as sysExit
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QCursor
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QHBoxLayout, QVBoxLayout, QDockWidget, QStyleFactory
from PyQt5.QtWidgets import QPushButton, QLineEdit, QLabel, QSlider, QTextBrowser, QMenuBar, QStatusBar
class MenuToolBar(QDockWidget):
def __init__(self, MainWin):
QDockWidget.__init__(self)
self.MainWin = MainWin
self.MainMenu = MainWin.menuBar()
# ******* Create the Help Menu *******
self.HelpMenu = self.MainMenu.addMenu('Help')
class CenterPanel(QWidget):
def __init__(self, parent):
QWidget.__init__(self)
# General Font Object for a couple of Buttons
btnFont = QFont()
btnFont.setFamily('Arial')
btnFont.setItalic(True)
# First Item Horizontal Box 1 Containing the AddLib Entry and Button
self.lnAdlibEntry = QLineEdit(self)
# self.lnAdlibEntry.setGeometry(QRect(30, 20, 501, 51))
# self.lnAdlibEntry.resize(501, 51)
self.btnAddLine = QPushButton(self)
# Left, Top, Width, Height
# self.btnAddLine.setGeometry(QRect(530, 0, 91, 51))
# Width, Height
# self.btnAddLine.resize(91, 51)
self.btnAddLine.setFont(btnFont)
self.btnAddLine.setCursor(QCursor(Qt.PointingHandCursor))
self.btnAddLine.setText('Adlib')
self.btnAddLine.clicked.connect(parent.AddLineAdlib)
HBox1 = QHBoxLayout()
HBox1.addWidget(self.lnAdlibEntry)
HBox1.addWidget(self.btnAddLine)
# Second Item Vertical Box 1 Containing the AdlibEntry LineEdit and RTD Label and RTD Slider
self.lblDial = QLabel(self)
# self.lblDial.setGeometry(QRect(640, 20, 71, 16))
# self.lblDial.resize(71, 16)
self.lblDial.setText("RTD Level")
self.sldrRtd = QSlider(self)
# self.sldrRtd.setGeometry(QRect(620, 40, 101, 22))
# self.sldrRtd.resize(101, 22)
self.sldrRtd.setOrientation(Qt.Horizontal)
VBox1 = QVBoxLayout()
VBox1.addWidget(self.lblDial)
VBox1.addWidget(self.sldrRtd)
# Third Item Horizontal Box 2 containing the Save, No Adlib and Delete buttons
self.btnNoAdlib = QPushButton(self)
# self.btnNoAdlib.setGeometry(QRect(530, 50, 91, 51))
# self.btnNoAdlib.resize(91, 51)
self.btnNoAdlib.setFont(btnFont)
self.btnNoAdlib.setCursor(QCursor(Qt.PointingHandCursor))
self.btnNoAdlib.setText("No Adlib")
self.btnSave = QPushButton(self)
# self.btnSave.setGeometry(QRect(30, 80, 91, 32))
# self.btnSave.resize(91, 32)
self.btnSave.setCursor(QCursor(Qt.PointingHandCursor))
self.btnSave.setText('Save')
self.btnDelete = QPushButton(self)
# self.btnDelete.setGeometry(QRect(120, 80, 91, 32))
# self.btnDelete.resize(91, 32)
self.btnDelete.setCursor(QCursor(Qt.PointingHandCursor))
self.btnDelete.setText('Delete')
HBox2 = QHBoxLayout()
HBox2.addWidget(self.btnSave)
HBox2.addStretch(1)
HBox2.addWidget(self.btnNoAdlib)
HBox2.addStretch(1)
HBox2.addWidget(self.btnDelete)
# Sixth Item Text Browser
self.txtBrowser = QTextBrowser(self)
# self.txtBrowser.setGeometry(QRect(20, 120, 701, 501))
# self.txtBrowser.resize(701, 501)
VBox2 = QVBoxLayout()
VBox2.addLayout(HBox1)
VBox2.addLayout(VBox1)
VBox2.addLayout(HBox2)
VBox2.addWidget(self.txtBrowser)
self.setLayout(VBox2)
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.Lyrics = ''
self.Adlib = ' (Placeholder adlib)'
self.setWindowTitle('Main Window')
self.resize(742, 680)
self.CenterPane = CenterPanel(self)
self.setCentralWidget(self.CenterPane)
self.MenuBar = MenuToolBar(self)
# self.MenuBar.setGeometry(QRect(0, 0, 742, 22))
self.SetStatusBar(self)
self.setStyle(QStyleFactory.create('Cleanlooks'))
def SetStatusBar(self, parent):
StatusMsg = ''
parent.StatBar = parent.statusBar()
if len(StatusMsg) < 1:
StatusMsg = 'Ready'
parent.StatBar.showMessage(StatusMsg)
def AddLineAdlib(self):
# This statement retains everything previously in Lyrics and
# everything in the AdlibEntry box and everything in Adlib which
# I am not sure is what you are wanting but it is what you had
self.Lyrics += self.CenterPane.lnAdlibEntry.text() + self.Adlib + '\n'
self.CenterPane.lnAdlibEntry.clear()
self.CenterPane.txtBrowser.setText(self.Lyrics)
def AddLineNoAdlib(self):
pass
def Save(self):
pass
def DeleteLine(self):
pass
if __name__ == "__main__":
MainThred = QApplication([])
MainGUI = MainWindow()
MainGUI.show()
sysExit(MainThred.exec_())
Edited: I had an odd arrow appearing on my screen which it appears the QStyleFactory call removes and I adjust the StatusBar declaration to be more modular in case you want to Class-ify it later
Here is what I do : I have a png plan for different sections in a library. In PyQt5 I have a button for each section which when pressed alternates the base png with a copy that has the corresponding section highlighted.
See my code below for my caveman solution to the problem.
It works but if I click the cdLoc button but don't wait for it to end and press the dvdLoc, dvdLoc will run through then will finish running cdLoc, highlighting the wrong section.
So my question - aside from any recommendations to better do this job - is whether there is a way to make functions run one at a time or forbid any other functions from launching while I'm running a specific function?
EDIT : I coudn't add the png files so instead I have it print the button output to the console. If you click Cds then Dvds before the first one is other, it will prints Cds at the end.
from PyQt5 import QtCore, QtGui, QtWidgets, QtTest
from PyQt5.QtGui import QIcon, QPixmap
import time
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 662)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label = QtWidgets.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(10, 10, 640, 562))
self.label.setFrameShape(QtWidgets.QFrame.Box)
self.label.setText("")
self.label.setObjectName("label")
pixmap = QPixmap('blank.png')
self.label.setPixmap(pixmap)
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(160, 580, 334, 32))
font = QtGui.QFont()
font.setFamily("Segoe UI")
font.setPointSize(18)
self.label_2.setFont(font)
self.label_2.setObjectName("label_2")
self.cds = QtWidgets.QPushButton(self.centralwidget)
self.cds.setGeometry(QtCore.QRect(650, 130, 141, 23))
self.cds.setObjectName("cds")
self.dvd = QtWidgets.QPushButton(self.centralwidget)
self.dvd.setGeometry(QtCore.QRect(650, 160, 141, 23))
self.dvd.setObjectName("dvd")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.cds.clicked.connect(self.cdLoc)
self.dvd.clicked.connect(self.dvdLoc)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "Library Plan"))
self.label_2.setText(_translate("MainWindow", "Library plan"))
self.cds.setText(_translate("MainWindow", "Cds"))
self.dvd.setText(_translate("MainWindow", "Dvds"))
def cdLoc(self):
print('cd') # I had to replace my code but so it can be tested but the orignal code uses these two lines instead of printing : pixmap = Pixmap('pictureName.png') and self.label.setPixmap(pixmap)
QtTest.QTest.qWait(1000)
print('base')
QtTest.QTest.qWait(500)
print('cd')
QtTest.QTest.qWait(1000)
print('base')
QtTest.QTest.qWait(500)
print('cd')
def dvdLoc(self):
print('dvd')
QtTest.QTest.qWait(1000)
print('base')
QtTest.QTest.qWait(500)
print('dvd')
QtTest.QTest.qWait(1000)
print('base')
QtTest.QTest.qWait(500)
print('dvd')
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
enabled : bool
This property holds whether the widget is enabled
In general an enabled widget handles keyboard and mouse events; a disabled widget does not.
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5 import QtTest
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.label = QLabel()
self.cdLocButton = QPushButton('cdLocButton')
self.cdLocButton.clicked.connect(self.cdLoc)
self.dvdLocButton = QPushButton('dvdLocButton')
self.dvdLocButton.clicked.connect(self.dvdLoc)
layout = QVBoxLayout(self)
layout.addWidget(self.label)
layout.addWidget(self.cdLocButton)
layout.addWidget(self.dvdLocButton)
def cdLoc(self):
self.dvdLocButton.setEnabled(False) # <---
pixmap = QPixmap('Ok.png')
self.label.setPixmap(pixmap)
QtTest.QTest.qWait(1000)
pixmap = QPixmap('im.png')
self.label.setPixmap(pixmap)
QtTest.QTest.qWait(500)
pixmap = QPixmap('Ok.png')
self.label.setPixmap(pixmap)
QtTest.QTest.qWait(1000)
pixmap = QPixmap('im.png')
self.label.setPixmap(pixmap)
QtTest.QTest.qWait(500)
pixmap = QPixmap('Ok.png')
self.label.setPixmap(pixmap)
self.dvdLocButton.setEnabled(True) # <---
def dvdLoc(self):
self.cdLocButton.setEnabled(False)
pixmap = QPixmap('exit.png')
self.label.setPixmap(pixmap)
QtTest.QTest.qWait(1000)
pixmap = QPixmap('save.png')
self.label.setPixmap(pixmap)
QtTest.QTest.qWait(500)
pixmap = QPixmap('exit.png')
self.label.setPixmap(pixmap)
QtTest.QTest.qWait(1000)
pixmap = QPixmap('save.png')
self.label.setPixmap(pixmap)
QtTest.QTest.qWait(500)
pixmap = QPixmap('exit.png')
self.label.setPixmap(pixmap)
self.cdLocButton.setEnabled(True)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
What I'm doing is about that when I clicked the date of the
calendar ,then it will display the class of UI_tab which is a tabwidget ,including two tabs.each tab includes some labels and others.However it
cant't work.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Tab(object):
# create tabwidget
def __init__(self,parentw,*args):
print(args)
print(parentw)
super().__init__()
self.font = QtGui.QFont()
self.font.setFamily("仿宋")
self.font.setPointSize(10)
self.font.setItalic(False)
self.font.setUnderline(False)
self.w=['title0','title1',
'creator0','creator1',
'c_time0','c_time1',
'user0','user1',
'd_time0','d_time1',
'detail0']
self.wt=['title','creator','create_time',
'viewer','finish_time','detail']
self.tabWidget = QtWidgets.QTabWidget(parentw)
self.tabWidget.setGeometry(QtCore.QRect(50, 10, 500, 2500))
self.tabWidget.setMinimumSize(QtCore.QSize(400, 400))
self.tabWidget.setTabsClosable(False)
self.tabWidget.setMovable(True)
self.tabWidget.setObjectName("tabWidget")
self.initTab()
# create tabs in tabwidget
def initTab(self,tabnum=2):
self.tabnum=tabnum
print('inittab')
self.tabs={}
for i in range(self.tabnum):
self.tabs[str(i)]=QtWidgets.QWidget()
self.tabs[str(i)].setObjectName("tab"+str(i))
self.tabWidget.addTab(self.tabs[str(i)], "")
self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabs[str(i)]),str(i))
self.initw_in_tab(self.tabs[str(i)])
print(self.tabs)
# add labels,textbrowser in tabs
def initw_in_tab(self,parentw):
w_in_tab={}
print('initw_in_tab')
for i in self.w:
w_in_tab[i]=QtWidgets.QLabel(parentw)
w_in_tab[i].setFont(self.font)
w_in_tab[i].setLayoutDirection(QtCore.Qt.LeftToRight)
w_in_tab[i].setAutoFillBackground(False)
w_in_tab[i].setFrameShape(QtWidgets.QFrame.Box)
w_in_tab[i].setFrameShadow(QtWidgets.QFrame.Raised)
w_in_tab[i].setLineWidth(1)
w_in_tab[i].setMidLineWidth(0)
w_in_tab[i].setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
w_in_tab[i].setIndent(3)
w_in_tab[i].setObjectName(i)
if self.w.index(i)%2 ==0:
w_in_tab[i].setGeometry(QtCore.QRect(20, 180 + self.w.index(i)*25, 59, 25))
w_in_tab[i].setText(self.wt[int(self.w.index(i)/2)])
else:
w_in_tab[i].setGeometry(QtCore.QRect(140, 180 +(self.w.index(i)-1)*25, 59, 25))
scrollArea = QtWidgets.QScrollArea(parentw)
scrollArea.setEnabled(True)
scrollArea.setGeometry(QtCore.QRect(140, 7*25+180, 341, 440))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(scrollArea.sizePolicy().hasHeightForWidth())
scrollArea.setSizePolicy(sizePolicy)
scrollArea.setMinimumSize(QtCore.QSize(200, 100))
scrollArea.setWidgetResizable(True)
scrollArea.setObjectName("scrollArea")
scrollAreaWidgetContents_2 = QtWidgets.QWidget()
scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 322, 1600))
scrollAreaWidgetContents_2.setMinimumSize(QtCore.QSize(200, 1600))
scrollAreaWidgetContents_2.setObjectName("scrollAreaWidgetContents_2")
detail2 = QtWidgets.QTextBrowser(scrollAreaWidgetContents_2)
detail2.setGeometry(QtCore.QRect(0, 0, 321, 600))
detail2.setMinimumSize(QtCore.QSize(296, 192))
detail2.setObjectName("detail2")
scrollArea.setWidget(scrollAreaWidgetContents_2)
class Ui_MainWindow(object):
# setup main ui include calendar
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(997, 707)
MainWindow.setStyleSheet("")
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.centralWidget.setUpdatesEnabled(True)
self.calendarw = QtWidgets.QWidget(self.centralWidget)
self.calendarw.setGeometry(QtCore.QRect(560, 20, 361, 541))
self.calendarw.setObjectName("calendarw")
self.cal = QtWidgets.QCalendarWidget(self.calendarw)
self.cal.setGeometry(QtCore.QRect(0, 60, 361, 481))
self.cal.setFirstDayOfWeek(QtCore.Qt.Monday)
self.cal.setObjectName("cal")
self.cal_la = QtWidgets.QLabel(self.calendarw)
self.cal_la.setGeometry(QtCore.QRect(110, 20, 161, 31))
font = QtGui.QFont()
font.setPointSize(22)
self.cal_la.setFont(font)
self.cal_la.setAlignment(QtCore.Qt.AlignCenter)
self.cal_la.setObjectName("cal_la")
MainWindow.setCentralWidget(self.centralWidget)
MainWindow.setWindowTitle("MainWindow")
self.cal_la.setText("calendar")
#
# Ui_Tab(self.centralWidget)
# this makes me confused,I hope that when I clicked the date of the
# calendar ,then it will display the class of UI_tab.However it
# cant't work.
self.cal.clicked.connect(lambda x :Ui_Tab(self.centralWidget))
QtCore.QMetaObject.connectSlotsByName(MainWindow)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
when I use the below code , it exactly does what I want it to do, but without clicking the calendar date.
Ui_Tab(self.centralWidget)
instead of
self.cal.clicked.connect(lambda x :Ui_Tab(self.centralWidget))
visit PyQt Window No Show
I just change the code below
self.cal.clicked.connect(lambda x :Ui_Tab(self.centralWidget))
to
self.cal.clicked.connect(Ui_Tab(self.centralWidget).show)