Cannot set header labels in tableview - python-3.x

So I want to change the labels of the tableview but keep getting an error when using the code I have found on other questions.
I am using the setHorizontalHeaderLabels code to add them.
class Setup(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(Setup, self).__init__(parent)
self.setWindowIcon(QtGui.QIcon('icon.png'))
self.initUI()
def initUI(self):
self.setWindowTitle('Auto-Annoucement - Setup')
self.showMaximized()
self.createTable()
self.setupmon = QWidget()
self.setup_layout = QVBoxLayout(self.setupmon)
self.setup_layout.addWidget(self.tableViewmon)
def createTable(self):
self.modelmon = QtGui.QStandardItemModel(self)
self.modelmon.setHorizontalHeaderLabels(self, ['Time', 'File Name'])
self.tableViewmon = QtWidgets.QTableView(self)
self.tableViewmon.setModel(self.modelmon)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
setup = Setup()
setup.show()
sys.exit(app.exec_())
I keep getting the error:
TypeError: setHorizontalHeader(self, QHeaderView): argument 1 has unexpected type 'Setup'

void QTableWidget::setHorizontalHeaderLabels(const QStringList &labels)
Sets the horizontal header labels using labels.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Setup(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(Setup, self).__init__(parent)
self.setWindowIcon(QtGui.QIcon('icon.png'))
self.initUI()
def initUI(self):
self.setWindowTitle('Auto-Annoucement - Setup')
self.showMaximized()
self.createTable()
self.setupmon = QtWidgets.QWidget()
self.setCentralWidget(self.setupmon) # +++
self.setup_layout = QtWidgets.QVBoxLayout(self.setupmon)
self.setup_layout.addWidget(self.tableViewmon)
def createTable(self):
self.modelmon = QtGui.QStandardItemModel(self)
# self.modelmon.setHorizontalHeaderLabels(self, ['Time', 'File Name'])
self.modelmon.setHorizontalHeaderLabels(['Time', 'File Name']) # +++
self.tableViewmon = QtWidgets.QTableView(self)
self.tableViewmon.setModel(self.modelmon)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
setup = Setup()
setup.show()
sys.exit(app.exec_())

Related

pyqt signal from a window not changing the main window widgets

I can pass values between two windows using signal,
and I want the plain text change, while I press a button from another window.
but the insertPlainText and even text.show() are not working
I've tried sending the signal to the init part of the Mainwindow,
tried update, repaint, but none of them works.
appreciate for any of your help, thanks!
the search_send method in class SearchWindow to MainWindow method test_
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.ui.tag_box.hide()
def test_(self, i): # -------problem here------------------
print(i) // <- value here were right
self.ui.tag_box.insertPlainText(i) # -------Plain Text does not change-------
self.ui.tag_box.show()# -------Plain Text does not show either--------------
class SearchWindow(QtWidgets.QMainWindow):
signal=pyqtSignal(str)
def __init__(self, endpoint=None, user=None, password=None, points_link=None):
super(SearchWindow, self).__init__()
self.ui = Ui_Search()
self.ui.setupUi(self)
self.ui.pushButton_2.clicked.connect(self.search_send)
def search_send(self): # -------problem here------------------
tag_list = [tag1,tag2, tag3]
otherClass = MainWindow()
self.signal.connect(otherClass.test_)
for k in tag_list:
self.signal.emit(k)
if __name__ == '__main__':
app = QtWidgets.QApplication([])
window = MainWindow()
window.show()
sys.exit(app.exec_())
As we're unclear what Ui_Dialog contains, I can't tell what's wrong exactly, but can show you how Signal should be used.
This is example of Signal that's transferring text to Slot. Name may differ in PyQt5 - change accordingly.
from PySide2.QtWidgets import QWidget, QApplication, QPlainTextEdit, QTextEdit, QVBoxLayout
from PySide2.QtCore import Signal, Slot
import sys
class MainWindow(QWidget):
sig = Signal(str)
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowTitle("Main")
self.layout = QVBoxLayout()
self.text = QTextEdit()
self.layout.addWidget(self.text)
self.setLayout(self.layout)
self.text.textChanged.connect(self.onChange)
def onChange(self):
self.sig.emit(self.text.toPlainText())
class SubWindow(QWidget):
def __init__(self, connect_target: MainWindow):
super(SubWindow, self).__init__()
self.setWindowTitle("Sub")
self.layout = QVBoxLayout()
self.text = QPlainTextEdit()
self.layout.addWidget(self.text)
self.setLayout(self.layout)
connect_target.sig.connect(self.onSignal)
#Slot(str)
def onSignal(self, text):
self.text.insertPlainText(text + '\r\n')
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
window_sub = SubWindow(window)
window_sub.show()
sys.exit(app.exec_())
Anything inside Main will be inserted to QPlainTextEdit as you wanted.

How to make "finish" button in QStackedWidget

I trying to create "Finish" button in QStackedWidget.
In a "checkButtons" function i checking current page index and set click events and text. I tried to check it by class name, but it doesn't work too.
Here is a code:
import sys
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import (QApplication, QDialog, QComboBox, QStackedWidget, QWidget,
QPushButton, QLabel, QVBoxLayout, QHBoxLayout, QStyle)
class Main(QDialog):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
# Main window setup
self.setWindowTitle("Stacked widget example")
self.setWindowIcon(self.style().standardIcon(QStyle.SP_FileDialogNewFolder))
self.setMinimumSize(400, 400)
self.setMaximumSize(640, 480)
self.rootVBox = QVBoxLayout()
self.rootHBox = QHBoxLayout()
self.rootHBox.addStretch()
self.rootVBox.addStretch()
self.pages = [FirstPage, SecondPage]
self.stacked = QStackedWidget(self)
for i in self.pages: self.stacked.addWidget(i(self))
self.pageState = True
self.buttonNext = QPushButton("Next")
self.buttonNext.clicked.connect(self.buttonNextConnect)
self.buttonBack = QPushButton("Back")
self.buttonBack.clicked.connect(self.buttonBackConnect)
self.rootHBox.addWidget(self.buttonBack)
self.rootHBox.addWidget(self.buttonNext)
self.rootVBox.addLayout(self.rootHBox)
self.setLayout(self.rootVBox)
def checkButtons(self):
print(self.stacked.currentIndex())
# I tried to check self.stacked.currentIndex() but it didn't work too
# if self.stacked.currentWidget().__class__ == self.pages[-1]:
if self.stacked.currentIndex() == len(self.pages) - 1:
self.buttonNext.setText("Finish")
self.buttonNext.clicked.connect(self.close)
elif self.stacked.currentIndex() < len(self.pages) - 1:
self.buttonNext.setText("Next")
self.buttonNext.clicked.connect(self.buttonNextConnect)
def buttonNextConnect(self):
self.stacked.setCurrentIndex(self.stacked.currentIndex() + 1)
self.checkButtons()
def buttonBackConnect(self):
self.stacked.setCurrentIndex(self.stacked.currentIndex() - 1)
self.checkButtons()
def finish(self):
self.close()
class FirstPage(QWidget):
def __init__(self, parent=None):
super(FirstPage, self).__init__(parent)
label = QLabel("First page")
rootVBox = QVBoxLayout()
rootHBox = QHBoxLayout()
rootHBox.addWidget(label)
rootVBox.addLayout(rootHBox)
self.setLayout(rootVBox)
class SecondPage(QWidget):
def __init__(self, parent=None):
super(SecondPage, self).__init__(parent)
label = QLabel("Second page")
rootVBox = QVBoxLayout()
rootHBox = QHBoxLayout()
rootHBox.addWidget(label)
rootVBox.addLayout(rootHBox)
self.setLayout(rootVBox)
if __name__ == '__main__':
app = QApplication(sys.argv)
main = Main()
main.show()
sys.exit(app.exec_())
If you try to press "next", "back" and then "next" again a program will be close. So, how can i fix it? Should i just make control buttons for each widget?
You must use the currentChanged signal of the QStackedWidget to know what page you are on and thus change the text, but in the buttonNextConnect slot you should check if you are already on the last page before switching to a new page, if you are then call to finish and if you do not change to another page
class Main(QDialog):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
# Main window setup
self.setWindowTitle("Stacked widget example")
self.setWindowIcon(self.style().standardIcon(QStyle.SP_FileDialogNewFolder))
self.setMinimumSize(400, 400)
self.setMaximumSize(640, 480)
rootVBox = QVBoxLayout(self)
rootHBox = QHBoxLayout()
rootHBox.addStretch()
rootVBox.addStretch()
self.pages = [FirstPage, SecondPage]
self.stacked = QStackedWidget(self)
for i in self.pages: self.stacked.addWidget(i(self))
self.buttonNext = QPushButton("Next")
self.buttonNext.clicked.connect(self.buttonNextConnect)
self.buttonBack = QPushButton("Back")
self.buttonBack.clicked.connect(self.buttonBackConnect)
rootHBox.addWidget(self.buttonBack)
rootHBox.addWidget(self.buttonNext)
rootVBox.addLayout(rootHBox)
self.stacked.currentChanged.connect(self.on_currentChanged)
def buttonNextConnect(self):
if self.stacked.currentIndex() == self.stacked.count() -1:
self.finish()
if self.stacked.currentIndex() < self.stacked.count() -1:
self.stacked.setCurrentIndex(self.stacked.currentIndex() + 1)
def buttonBackConnect(self):
if self.stacked.currentIndex() > 0:
self.stacked.setCurrentIndex(self.stacked.currentIndex() - 1)
def on_currentChanged(self, index):
if index == self.stacked.count() -1:
self.buttonNext.setText("Finish")
else:
self.buttonNext.setText("Next")
def finish(self):
self.close()
Another option is to use QWizard and QWizardPage:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Main(QtWidgets.QWizard):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
buttons = [
QtWidgets.QWizard.Stretch,
QtWidgets.QWizard.BackButton,
QtWidgets.QWizard.NextButton,
QtWidgets.QWizard.FinishButton
]
self.setButtonLayout(buttons)
self.addPage(FirstPage())
self.addPage(SecondPage())
class FirstPage(QtWidgets.QWizardPage):
def __init__(self, parent=None):
super(FirstPage, self).__init__(parent)
self.setTitle("First page")
class SecondPage(QtWidgets.QWizardPage):
def __init__(self, parent=None):
super(SecondPage, self).__init__(parent)
self.setTitle("Second page")
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
main = Main()
main.show()
sys.exit(app.exec_())

pyqt4 Main window crashes after second window closes

I've got this simple program. Its has a button and when you press it a second window will come up.
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
import urllib.request
class second_window(QDialog):
def __init__(self, parent=None):
QDialog.__init__(self)
super(second_window, self).__init__(parent)
layout = QVBoxLayout()
button = QPushButton("close")
button.clicked.connect(self.button_clicked)
layout.addWidget(button)
self.setLayout(layout)
def button_clicked(self):
self.close()
class Main_window(QDialog):
def __init__(self):
QDialog.__init__(self)
layout = QVBoxLayout()
button = QPushButton("Second Window")
self.sec_window = second_window(self)
layout.addWidget(button)
button.clicked.connect(self.button_clicked)
self.setLayout(layout)
def button_clicked(self):
self.sec_window.exec_()
if __name__ == "__main__":
app = QApplication(sys.argv)
dl = window()
dl.show()
app.exec()
But sometimes if you close the Main_window just after you close the second_window it crashes and I get a message saying "Python.exe has stopped working".
can anyone help?
First Solution: Change self.sec_window = second_window(self) to self.sec_window = second_window() since it will not be necessary to clean because there is no relationship between second_window and Main_window. As the following code shows
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
class second_window(QDialog):
def __init__(self, parent=None):
QDialog.__init__(self)
super(second_window, self).__init__(parent)
layout = QVBoxLayout()
button = QPushButton("close")
button.clicked.connect(self.button_clicked)
layout.addWidget(button)
self.setLayout(layout)
def button_clicked(self):
self.close()
class Main_window(QDialog):
def __init__(self):
QDialog.__init__(self)
layout = QVBoxLayout()
button = QPushButton("Second Window")
self.sec_window = second_window()
layout.addWidget(button)
button.clicked.connect(self.button_clicked)
self.setLayout(layout)
def button_clicked(self):
self.sec_window.exec_()
if __name__ == "__main__":
app = QApplication(sys.argv)
dl = Main_window()
dl.show()
app.exec()
Second Solution: Add self.sec_window.deleteLater() on closeEvent(self, event) to be able to delete second_window
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
class second_window(QDialog):
def __init__(self, parent=None):
QDialog.__init__(self)
super(second_window, self).__init__(parent)
layout = QVBoxLayout()
button = QPushButton("close")
button.clicked.connect(self.button_clicked)
layout.addWidget(button)
self.setLayout(layout)
def button_clicked(self):
self.close()
class Main_window(QDialog):
def __init__(self):
QDialog.__init__(self)
layout = QVBoxLayout()
button = QPushButton("Second Window")
self.sec_window = second_window(self)
layout.addWidget(button)
button.clicked.connect(self.button_clicked)
self.setLayout(layout)
def button_clicked(self):
self.sec_window.exec_()
def closeEvent(self, event):
self.sec_window.deleteLater()
super().closeEvent(event)
if __name__ == "__main__":
app = QApplication(sys.argv)
dl = Main_window()
dl.show()
app.exec()

TypeError: 'QLabel' object is not callable

When I run the demo program as below, the mainwindow will call the childwindow, then the childwindow will call a widget. I want to get some attribute of this widget such as "messageLabel",but it will report an error that TypeError: 'QLabel' object is not callable. Then how to modify this error? Thank you,
import sys
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__()
self.setWindowTitle("MainWindow Window!")
self.setGeometry(400, 400, 100, 100)
self.centerWidget = QtGui.QWidget()
self.setCentralWidget(self.centerWidget)
self.pushButton = QtGui.QPushButton("&Button")
layout = QtGui.QVBoxLayout()
layout.addWidget(self.pushButton)
self.centerWidget.setLayout(layout)
class ChildWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(ChildWindow, self).__init__(parent)
#QtGui.QMainWindow.__init__(self, parent)
self.setWindowTitle("Child Window!")
self.centerWidget = Widget(parent)
self.setCentralWidget(self.centerWidget)
class Widget(QtGui.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__()
self.messageLabel = QtGui.QLabel()
self.messageLabel.setText("How to get this message label?")
layout = QtGui.QVBoxLayout()
layout.addWidget(self.messageLabel)
self.setLayout(layout)
app = QtGui.QApplication(sys.argv)
myapp = MainWindow()
def showChildWindow():
child_win = ChildWindow(myapp)
child_win.show()
childLabel = child_win.centerWidget.messageLabel().text().__str__().__str__() #how to call the messageLabel?
print childLabel
myapp.show()
QtCore.QObject.connect(myapp.pushButton,QtCore.SIGNAL("clicked()"),showChildWindow)
sys.exit(app.exec_())

How do I auto fit a Matplotlib figure inside a PySide QFrame?

I'm creating a simple PySide application that also uses MatPlotLib. However, when I add the figure into a QFrame, the figure doesn't automatically fit to the frame:
My graph is created using the following code:
class GraphView(gui.QWidget):
def __init__(self, name, title, graphTitle, parent = None):
super(GraphView, self).__init__(parent)
self.name = name
self.graphTitle = graphTitle
self.dpi = 100
self.fig = Figure((5.0, 3.0), dpi = self.dpi, facecolor = (1,1,1), edgecolor = (0,0,0))
self.axes = self.fig.add_subplot(111)
self.canvas = FigureCanvas(self.fig)
self.Title = gui.QLabel(self)
self.Title.setText(title)
self.layout = gui.QVBoxLayout()
self.layout.addStretch(1)
self.layout.addWidget(self.Title)
self.layout.addWidget(self.canvas)
self.setLayout(self.layout)
def UpdateGraph(self, data, title = None):
self.axes.clear()
self.axes.plot(data)
if title != None:
self.axes.set_title(title)
self.canvas.draw()
And it's added to the main Widget like so:
# Create individual Widget/Frame (fftFrame)
fftFrame = gui.QFrame(self)
fftFrame.setFrameShape(gui.QFrame.StyledPanel)
self.FFTGraph = GraphView('fftFrame', 'FFT Transform:', 'FFT Transform of Signal', fftFrame)
Here's a working code sample that shows you how to get it working. I first thought it was because of the stretch you added to the layout, which will use up the additional space around the other widgets. But when I removed it, it still wouldn't resize. The 'easy' solution is to add a resizeEvent, which lets you define the size of your GraphView widget. In this case I just set its geometry to be that of the QFrame, though you might want to add some padding and make sure you set a sensible minimum size for the QFrame.
from PySide import QtGui
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import sys
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.fft_frame = FftFrame(self)
self.layout = QtGui.QVBoxLayout()
self.layout.addWidget(self.fft_frame)
self.setLayout(self.layout)
self.setCentralWidget(self.fft_frame)
class FftFrame(QtGui.QFrame):
def __init__(self, parent=None):
super(FftFrame, self).__init__(parent)
self.setFrameShape(QtGui.QFrame.StyledPanel)
self.parent = parent
self.graph_view = GraphView('fftFrame', 'FFT Transform:', 'FFT Transform of Signal', self)
def resizeEvent(self, event):
self.graph_view.setGeometry(self.rect())
class GraphView(QtGui.QWidget):
def __init__(self, name, title, graph_title, parent = None):
super(GraphView, self).__init__(parent)
self.name = name
self.graph_title = graph_title
self.dpi = 100
self.fig = Figure((5.0, 3.0), dpi = self.dpi, facecolor = (1,1,1), edgecolor = (0,0,0))
self.axes = self.fig.add_subplot(111)
self.canvas = FigureCanvas(self.fig)
self.canvas.setParent(self)
self.Title = QtGui.QLabel(self)
self.Title.setText(title)
self.layout = QtGui.QVBoxLayout()
self.layout.addWidget(self.Title)
self.layout.addWidget(self.canvas)
self.layout.setStretchFactor(self.canvas, 1)
self.setLayout(self.layout)
self.canvas.show()
def update_graph(self, data, title = None):
self.axes.clear()
self.axes.plot(data)
if title != None:
self.axes.set_title(title)
self.canvas.draw()
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

Resources