increase font size: import sys from PySide6.QtWidgets import ( QApplication,…
Jump to turn (6)
- User
increase font size: import sys from PySide6.QtWidgets import ( QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QTableView, QFrame ) from PySide6.QtGui import QStandardItemModel, QStandardItem from PySide6.QtCore import QEvent, QPoint, Qt import sqlite3
def run_query(query, parameters=()): # Run a SQLite query with sqlite3.connect('media.db') as conn: cursor = conn.cursor() result = cursor.execute(query, parameters) if query.strip().lower().startswith("select"): return result.fetchall() conn.commit()
def create_tables(): # Create necessary tables if they don't exist create_movies_table_sql = ''' CREATE TABLE IF NOT EXISTS movies ( id INTEGER PRIMARY KEY AUTOINCREMENT, movie TEXT, year TEXT, present BOOLEAN, watched BOOLEAN, notes TEXT ); ''' create_series_table_sql = ''' CREATE TABLE IF NOT EXISTS series ( id INTEGER PRIMARY KEY AUTOINCREMENT, series TEXT, seasons TEXT, year TEXT, present BOOLEAN, seasons_present TEXT, complete BOOLEAN, watched BOOLEAN, seasons_seen TEXT, notes TEXT ); ''' run_query(create_movies_table_sql) run_query(create_series_table_sql)
class MediaTracker(QMainWindow): def init(self): super().init()
self.setWindowTitle("Movies and Series Tracker")
self.setGeometry(200, 100, 1000, 600)
self.main_widget = QWidget(self)
self.setCentralWidget(self.main_widget)
self.main_layout = QHBoxLayout(self.main_widget)
# Sidebar with navigation buttons
self.sidebar_layout = QVBoxLayout()
self.main_layout.addLayout(self.sidebar_layout)
self.movies_button = QPushButton("Movies")
self.movies_button.clicked.connect(self.show_movies)
self.sidebar_layout.addWidget(self.movies_button)
self.series_button = QPushButton("Series")
self.series_button.clicked.connect(self.show_series)
self.sidebar_layout.addWidget(self.series_button)
self.sidebar_layout.addStretch()
# Button bar area (spacer for aesthetics and logical separation)
self.button_bar = QFrame()
self.button_bar.setFixedWidth(50)
self.button_bar.setStyleSheet("background-color: white;")
self.main_layout.addWidget(self.button_bar)
# Content layout for the table
self.content_layout = QVBoxLayout()
self.main_layout.addLayout(self.content_layout)
self.setup_movie_table()
self.setup_series_table()
# '+' and '-' buttons for current row
self.plus_button = QPushButton("+", self.button_bar)
self.plus_button.setFixedSize(20, 20)
self.plus_button.setVisible(False)
self.plus_button.raise_()
self.plus_button.clicked.connect(self.add_entry)
self.minus_button = QPushButton("-", self.button_bar)
self.minus_button.setFixedSize(20, 20)
self.minus_button.setVisible(False)
self.minus_button.raise_()
self.minus_button.clicked.connect(self.delete_entry)
self.current_row_id = None # To track the current hovered row ID
self.load_data()
self.show_movies()
# Connect the model's dataChanged signal to a slot for saving changes
self.movies_model.dataChanged.connect(self.save_movie_changes)
self.series_model.dataChanged.connect(self.save_series_changes)
def setup_movie_table(self):
self.movies_model = QStandardItemModel()
self.movies_columns = ["ID", "Movie", "Year", "Present", "Watched", "Notes"]
self.movies_model.setHorizontalHeaderLabels(self.movies_columns)
self.movies_table = QTableView()
self.movies_table.setModel(self.movies_model)
self.movies_table.setVerticalScrollMode(QTableView.ScrollPerPixel)
self.movies_table.setMouseTracking(True)
self.movies_table.viewport().installEventFilter(self)
self.movies_table.hideColumn(0) # Hides the ID column
self.content_layout.addWidget(self.movies_table)
def setup_series_table(self):
self.series_model = QStandardItemModel()
self.series_columns = ["ID", "Series", "Seasons", "Year", "Present", "Seasons Present",
"Complete", "Watched", "Seasons Seen", "Notes"]
self.series_model.setHorizontalHeaderLabels(self.series_columns)
self.series_table = QTableView()
self.series_table.setModel(self.series_model)
self.series_table.setVerticalScrollMode(QTableView.ScrollPerPixel)
self.series_table.setMouseTracking(True)
self.series_table.viewport().installEventFilter(self)
self.series_table.hideColumn(0) # Hides the ID column
def load_data(self):
if self.movies_table.isVisible():
self.load_movie_data()
else:
self.load_series_data()
def load_movie_data(self):
self.movies_model.removeRows(0, self.movies_model.rowCount())
movies_data = run_query('SELECT * FROM movies')
if not movies_data:
# Insert a default row if there are no entries in the table
run_query("INSERT INTO movies (movie, year, present, watched, notes) VALUES (?, ?, ?, ?, ?)",
('', '', None, None, ''))
movies_data = run_query('SELECT * FROM movies')
for row in movies_data:
items = [QStandardItem(str(data)) if data is not None else QStandardItem("") for data in row]
self.movies_model.appendRow(items)
def load_series_data(self):
self.series_model.removeRows(0, self.series_model.rowCount())
series_data = run_query('SELECT * FROM series')
if not series_data:
# Insert a default row if there are no entries in the table
run_query("INSERT INTO series (series, seasons, year, present, seasons_present, complete, watched, seasons_seen, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
('', '', '', None, '', None, None, '', ''))
series_data = run_query('SELECT * FROM series')
for row in series_data:
items = [QStandardItem(str(data)) if data is not None else QStandardItem("") for data in row]
self.series_model.appendRow(items)
def show_movies(self):
self.clear_content()
self.content_layout.addWidget(self.movies_table)
self.load_movie_data()
def show_series(self):
self.clear_content()
self.content_layout.addWidget(self.series_table)
self.load_series_data()
def add_entry(self):
if self.movies_table.isVisible():
run_query("INSERT INTO movies (movie, year, present, watched, notes) VALUES (?, ?, ?, ?, ?)",
('', '', None, None, ''))
self.load_movie_data()
elif self.series_table.isVisible():
run_query("INSERT INTO series (series, seasons, year, present, seasons_present, complete, watched, seasons_seen, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
('', '', '', None, '', None, None, '', ''))
self.load_series_data()
def delete_entry(self):
if self.current_row_id is not None:
if self.movies_table.isVisible():
run_query("DELETE FROM movies WHERE id = ?", (self.current_row_id,))
self.load_movie_data()
elif self.series_table.isVisible():
run_query("DELETE FROM series WHERE id = ?", (self.current_row_id,))
self.load_series_data()
def clear_content(self):
# Remove current content
for i in reversed(range(self.content_layout.count())):
widget_to_remove = self.content_layout.itemAt(i).widget()
self.content_layout.removeWidget(widget_to_remove)
if widget_to_remove is not None:
widget_to_remove.setParent(None)
def eventFilter(self, source, event):
if event.type() == QEvent.Type.MouseMove:
table = self.movies_table if self.movies_table.isVisible() else self.series_table
if source is table.viewport():
self.update_buttons_position(table, event.position().toPoint())
return super(MediaTracker, self).eventFilter(source, event)
def update_buttons_position(self, table, pos):
index = table.indexAt(pos)
if index.isValid():
row_index = index.row()
self.current_row_id = table.model().index(row_index, 0).data() # Fetch the ID for the current row
rect = table.visualRect(index)
# Center the buttons vertically within the row
y_pos = rect.top() + (rect.height() - self.plus_button.height()) // 2
# Calculate x-position for centering buttons horizontally within the button bar
button_spacing = 5
button_bar_center = self.button_bar.width() // 2
combined_button_widths = self.plus_button.width() + self.minus_button.width() + button_spacing
first_button_x = button_bar_center - (combined_button_widths // 2)
self.plus_button.move(first_button_x, y_pos)
self.minus_button.move(first_button_x + self.plus_button.width() + button_spacing, y_pos)
self.plus_button.setVisible(True)
self.minus_button.setVisible(True)
else:
self.plus_button.setVisible(False)
self.minus_button.setVisible(False)
self.current_row_id = None
def save_movie_changes(self, start_index, end_index):
for row in range(start_index.row(), end_index.row() + 1):
id_data = self.movies_model.item(row, 0).text()
movie_data = self.movies_model.item(row, 1).text()
year_data = self.movies_model.item(row, 2).text() # Now text
present_data = self.get_bool_value(self.movies_model.item(row, 3))
watched_data = self.get_bool_value(self.movies_model.item(row, 4))
notes_data = self.movies_model.item(row, 5).text()
run_query("UPDATE movies SET movie = ?, year = ?, present = ?, watched = ?, notes = ? WHERE id = ?",
(movie_data, year_data, present_data, watched_data, notes_data, id_data))
def save_series_changes(self, start_index, end_index):
for row in range(start_index.row(), end_index.row() + 1):
id_data = self.series_model.item(row, 0).text()
series_data = self.series_model.item(row, 1).text()
seasons_data = self.series_model.item(row, 2).text()
year_data = self.series_model.item(row, 3).text()
present_data = self.get_bool_value(self.series_model.item(row, 4))
seasons_present_data = self.series_model.item(row, 5).text()
complete_data = self.get_bool_value(self.series_model.item(row, 6))
watched_data = self.get_bool_value(self.series_model.item(row, 7))
seasons_seen_data = self.series_model.item(row, 8).text()
notes_data = self.series_model.item(row, 9).text()
run_query("UPDATE series SET series = ?, seasons = ?, year = ?, present = ?, seasons_present = ?, complete = ?, watched = ?, seasons_seen = ?, notes = ? WHERE id = ?",
(series_data, seasons_data, year_data, present_data, seasons_present_data, complete_data, watched_data, seasons_seen_data, notes_data, id_data))
def get_bool_value(self, item):
text = item.text().lower()
if text in ['true', '1']:
return True
elif text in ['false', '0']:
return False
return None
if name == "main": app = QApplication(sys.argv)
create_tables()
tracker = MediaTracker()
tracker.show()
sys.exit(app.exec())
To increase the font size in a PyQt application, you can apply stylesheets to the widgets. In this case, we can adjust the font size for the QTableView, QPushButton, or other widgets directly by setting a stylesheet. Below are the changes you can make to increase the font size:
Apply a stylesheet for general font settings. You can set a default font size for the entire application or specific widgets.
Specifically, for tables and buttons, you can directly set the font size using style sheets.
Here is an updated version of your code with increased font sizes for the table view and buttons:
# Add this line at the beginning of the __init__ method in your MediaTracker class
self.setStyleSheet("font-size: 14px;")
# Additional specific styling can be applied to table view and buttons if needed
self.movies_table.setStyleSheet("font-size: 14px;")
self.series_table.setStyleSheet("font-size: 14px;")
self.movies_button.setStyleSheet("font-size: 14px;")
self.series_button.setStyleSheet("font-size: 14px;")
self.plus_button.setStyleSheet("font-size: 14px;")
self.minus_button.setStyleSheet("font-size: 14px;")
# Alternatively, you can set a stylesheet globally at the end of the __init__ method to affect all widgets
self.setStyleSheet("""
QTableView {
font-size: 14px;
}
QPushButton {
font-size: 14px;
}
""")
This code increases the font size for QTableView and QPushButton to 14 pixels. You can adjust the font-size property to the size you prefer. Apply the stylesheet either directly on each widget or globally on the main window to ensure consistent styling throughout your application.
is there no easy global setting
In PyQt applications, there's no single global setting to adjust font size for all widgets explicitly through the API, primarily because each widget can have different styles or inherit styles based on what's assigned to it.
However, you can effectively implement a global font size setting by applying a stylesheet to the entire Qt application instance. This approach allows you to define default styles including font size for all widgets, providing a unified appearance across the application.
Here's how you can set a global font size using a stylesheet:
if __name__ == "__main__":
app = QApplication(sys.argv)
# Set a global stylesheet for the entire application
app.setStyleSheet("""
* {
font-size: 14px;
}
""")
create_tables()
tracker = MediaTracker()
tracker.show()
sys.exit(app.exec())
In this example, the * selector is used to apply a 14px font size to all widgets in the application by default. You can adjust the 14px to whatever size you prefer.
This method is the simplest way to globally change font size within a PyQt application without manually setting styles for each widget individually. However, note that specific widgets can still override the global style if needed by applying their own stylesheets.
what about like here: def create_widgets(self) -> None: """Initialize all GUI components."""
font = QFont()
font.setPointSize(12)
self.entry = QLineEdit()
self.entry.setFont(font)
self.entry.returnPressed.connect(self.calculate)
self.history_text = QTextEdit()
self.history_text.setFont(font)
self.history_text.setReadOnly(True)
self.scrollbar = QScrollBar(Qt.Vertical)
self.history_text.setVerticalScrollBar(self.scrollbar)
self.function_buttons = {
"Functions": ["sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "log", "ln"],
"Conversions": ["lb", "kg"],
"Unique": ["capitalize"],
"Constants": ["pi", "e"]
}
self.function_frame = QFrame()
self.create_function_buttons(font)
Using the QFont class to set a specific font size is another effective approach to apply font settings to individual widgets in PyQt. This method offers more granular control over the size and style that directly apply to each widget you instantiate.
Here's a breakdown of what you're doing in the provided code snippet and how you can use it to control font settings in various parts of your application:
Create a QFont instance: Instantiate a QFont object, where you can set various font properties, including the point size.
Set font properties: Use setPointSize() to define the font size for your application or specific widgets.
Apply the font to widgets: Use setFont() with your QFont instance for each widget. This customizes the font size along with any other properties you've set on the QFont object.
Here's a detailed explanation using your code structure:
from PySide6.QtGui import QFont
def create_widgets(self) -> None:
"""Initialize all GUI components."""
# Create a QFont instance and set the desired point size
font = QFont()
font.setPointSize(12) # You can adjust the size as needed
# Apply the font to individual widgets
self.entry = QLineEdit()
self.entry.setFont(font)
self.entry.returnPressed.connect(self.calculate)
self.history_text = QTextEdit()
self.history_text.setFont(font)
self.history_text.setReadOnly(True)
self.scrollbar = QScrollBar(Qt.Vertical)
self.history_text.setVerticalScrollBar(self.scrollbar)
self.function_buttons = {
"Functions": ["sqrt", "sin", "cos", "tan", "asin", "acos", "atan", "log", "ln"],
"Conversions": ["lb", "kg"],
"Unique": ["capitalize"],
"Constants": ["pi", "e"]
}
self.function_frame = QFrame()
self.create_function_buttons(font) # Pass the font to apply it to function buttons
def create_function_buttons(self, font):
# Assuming you have some logic here to create buttons, apply the font to each button
for category, functions in self.function_buttons.items():
for function in functions:
button = QPushButton(function)
button.setFont(font)
# Add more setup code for each button if needed
implement the QFont approach in the original code
To apply the QFont approach to your original code, you'll define a QFont instance and set its point size. Then, you will apply this font to your widgets — specifically the QTableView, QPushButton, and other relevant widgets. This method allows you to maintain a consistent font size across the application while still having the flexibility to adapt it for specific elements if needed.
Here's how you can implement this in your original code:
Print the new code in full
Certainly! Here is the full version of your code, updated to use the QFont approach for setting uniform font sizes across the widgets:
set literata as font
To set a specific font like "Literata" in a PyQt application using QFont, you'll need to ensure that the font is installed on your system. If it is, you can directly set the font family to "Literata" using QFont.setFamily().
Here's how you can modify the provided code to use "Literata" as the font:
Not yet included in a published release.
Consistency: By creating a QFont object and re-using it, you ensure that all your widgets follow the same font styling, leading to a consistent look and feel.
Granularity: You can easily choose to apply the font settings differently across components if needed. For instance, some widgets could use a larger or smaller font size or a different font family/style.
Reusability: This approach makes it easier to refactor and change the font settings in one place for multiple related widgets.
By setting the font for each component this way, you maintain clear and specific control over the appearance of each widget while still keeping it easy to modify later.
import sys
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QTableView, QFrame
)
from PySide6.QtGui import QStandardItemModel, QStandardItem, QFont
from PySide6.QtCore import QEvent, QPoint, Qt
import sqlite3
def run_query(query, parameters=()):
with sqlite3.connect('media.db') as conn:
cursor = conn.cursor()
result = cursor.execute(query, parameters)
if query.strip().lower().startswith("select"):
return result.fetchall()
conn.commit()
def create_tables():
create_movies_table_sql = '''
CREATE TABLE IF NOT EXISTS movies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
movie TEXT,
year TEXT,
present BOOLEAN,
watched BOOLEAN,
notes TEXT
);
'''
create_series_table_sql = '''
CREATE TABLE IF NOT EXISTS series (
id INTEGER PRIMARY KEY AUTOINCREMENT,
series TEXT,
seasons TEXT,
year TEXT,
present BOOLEAN,
seasons_present TEXT,
complete BOOLEAN,
watched BOOLEAN,
seasons_seen TEXT,
notes TEXT
);
'''
run_query(create_movies_table_sql)
run_query(create_series_table_sql)
class MediaTracker(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Movies and Series Tracker")
self.setGeometry(200, 100, 1000, 600)
# Create a QFont instance and set the desired point size
font = QFont()
font.setPointSize(12) # Adjust the font size as desired
self.main_widget = QWidget(self)
self.setCentralWidget(self.main_widget)
self.main_layout = QHBoxLayout(self.main_widget)
# Sidebar with navigation buttons
self.sidebar_layout = QVBoxLayout()
self.main_layout.addLayout(self.sidebar_layout)
self.movies_button = QPushButton("Movies")
self.movies_button.setFont(font)
self.movies_button.clicked.connect(self.show_movies)
self.sidebar_layout.addWidget(self.movies_button)
self.series_button = QPushButton("Series")
self.series_button.setFont(font)
self.series_button.clicked.connect(self.show_series)
self.sidebar_layout.addWidget(self.series_button)
self.sidebar_layout.addStretch()
# Button bar area (spacer for aesthetics and logical separation)
self.button_bar = QFrame()
self.button_bar.setFixedWidth(50)
self.button_bar.setStyleSheet("background-color: white;")
self.main_layout.addWidget(self.button_bar)
# Content layout for the table
self.content_layout = QVBoxLayout()
self.main_layout.addLayout(self.content_layout)
self.setup_movie_table(font)
self.setup_series_table(font)
# '+' and '-' buttons for current row
self.plus_button = QPushButton("+", self.button_bar)
self.plus_button.setFont(font)
self.plus_button.setFixedSize(20, 20)
self.plus_button.setVisible(False)
self.plus_button.raise_()
self.plus_button.clicked.connect(self.add_entry)
self.minus_button = QPushButton("-", self.button_bar)
self.minus_button.setFont(font)
self.minus_button.setFixedSize(20, 20)
self.minus_button.setVisible(False)
self.minus_button.raise_()
self.minus_button.clicked.connect(self.delete_entry)
self.current_row_id = None
self.load_data()
self.show_movies()
self.movies_model.dataChanged.connect(self.save_movie_changes)
self.series_model.dataChanged.connect(self.save_series_changes)
def setup_movie_table(self, font):
self.movies_model = QStandardItemModel()
self.movies_columns = ["ID", "Movie", "Year", "Present", "Watched", "Notes"]
self.movies_model.setHorizontalHeaderLabels(self.movies_columns)
self.movies_table = QTableView()
self.movies_table.setFont(font)
self.movies_table.setModel(self.movies_model)
self.movies_table.setVerticalScrollMode(QTableView.ScrollPerPixel)
self.movies_table.setMouseTracking(True)
self.movies_table.viewport().installEventFilter(self)
self.movies_table.hideColumn(0)
self.content_layout.addWidget(self.movies_table)
def setup_series_table(self, font):
self.series_model = QStandardItemModel()
self.series_columns = ["ID", "Series", "Seasons", "Year", "Present", "Seasons Present",
"Complete", "Watched", "Seasons Seen", "Notes"]
self.series_model.setHorizontalHeaderLabels(self.series_columns)
self.series_table = QTableView()
self.series_table.setFont(font)
self.series_table.setModel(self.series_model)
self.series_table.setVerticalScrollMode(QTableView.ScrollPerPixel)
self.series_table.setMouseTracking(True)
self.series_table.viewport().installEventFilter(self)
self.series_table.hideColumn(0)
# Rest of your class methods...
if __name__ == "__main__":
app = QApplication(sys.argv)
create_tables()
tracker = MediaTracker()
tracker.show()
sys.exit(app.exec())
QFont instance is created with the desired font size. This font object is then applied to all your buttons and tables to ensure consistency across the application.setFont(font) called with the previously defined QFont object.This approach offers a clean and reusable way to apply a consistent font size across all widgets affected by the font object.
import sys
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QTableView, QFrame
)
from PySide6.QtGui import QStandardItemModel, QStandardItem, QFont
from PySide6.QtCore import QEvent, QPoint, Qt
import sqlite3
def run_query(query, parameters=()):
# Run a SQLite query
with sqlite3.connect('media.db') as conn:
cursor = conn.cursor()
result = cursor.execute(query, parameters)
if query.strip().lower().startswith("select"):
return result.fetchall()
conn.commit()
def create_tables():
# Create necessary tables if they don't exist
create_movies_table_sql = '''
CREATE TABLE IF NOT EXISTS movies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
movie TEXT,
year TEXT,
present BOOLEAN,
watched BOOLEAN,
notes TEXT
);
'''
create_series_table_sql = '''
CREATE TABLE IF NOT EXISTS series (
id INTEGER PRIMARY KEY AUTOINCREMENT,
series TEXT,
seasons TEXT,
year TEXT,
present BOOLEAN,
seasons_present TEXT,
complete BOOLEAN,
watched BOOLEAN,
seasons_seen TEXT,
notes TEXT
);
'''
run_query(create_movies_table_sql)
run_query(create_series_table_sql)
class MediaTracker(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Movies and Series Tracker")
self.setGeometry(200, 100, 1000, 600)
# Create a QFont instance and set the desired font point size
font = QFont()
font.setPointSize(12) # Adjust font size as desired
self.main_widget = QWidget(self)
self.setCentralWidget(self.main_widget)
self.main_layout = QHBoxLayout(self.main_widget)
# Sidebar with navigation buttons
self.sidebar_layout = QVBoxLayout()
self.main_layout.addLayout(self.sidebar_layout)
self.movies_button = QPushButton("Movies")
self.movies_button.setFont(font)
self.movies_button.clicked.connect(self.show_movies)
self.sidebar_layout.addWidget(self.movies_button)
self.series_button = QPushButton("Series")
self.series_button.setFont(font)
self.series_button.clicked.connect(self.show_series)
self.sidebar_layout.addWidget(self.series_button)
self.sidebar_layout.addStretch()
# Button bar area
self.button_bar = QFrame()
self.button_bar.setFixedWidth(50)
self.button_bar.setStyleSheet("background-color: white;")
self.main_layout.addWidget(self.button_bar)
# Content layout for the table
self.content_layout = QVBoxLayout()
self.main_layout.addLayout(self.content_layout)
self.setup_movie_table(font)
self.setup_series_table(font)
# '+' and '-' buttons for current row
self.plus_button = QPushButton("+", self.button_bar)
self.plus_button.setFont(font)
self.plus_button.setFixedSize(20, 20)
self.plus_button.setVisible(False)
self.plus_button.raise_()
self.plus_button.clicked.connect(self.add_entry)
self.minus_button = QPushButton("-", self.button_bar)
self.minus_button.setFont(font)
self.minus_button.setFixedSize(20, 20)
self.minus_button.setVisible(False)
self.minus_button.raise_()
self.minus_button.clicked.connect(self.delete_entry)
self.current_row_id = None
self.load_data()
self.show_movies()
# Connect model's dataChanged signal to a slot for saving changes
self.movies_model.dataChanged.connect(self.save_movie_changes)
self.series_model.dataChanged.connect(self.save_series_changes)
def setup_movie_table(self, font):
self.movies_model = QStandardItemModel()
self.movies_columns = ["ID", "Movie", "Year", "Present", "Watched", "Notes"]
self.movies_model.setHorizontalHeaderLabels(self.movies_columns)
self.movies_table = QTableView()
self.movies_table.setFont(font)
self.movies_table.setModel(self.movies_model)
self.movies_table.setVerticalScrollMode(QTableView.ScrollPerPixel)
self.movies_table.setMouseTracking(True)
self.movies_table.viewport().installEventFilter(self)
self.movies_table.hideColumn(0) # Hides the ID column
self.content_layout.addWidget(self.movies_table)
def setup_series_table(self, font):
self.series_model = QStandardItemModel()
self.series_columns = ["ID", "Series", "Seasons", "Year", "Present", "Seasons Present",
"Complete", "Watched", "Seasons Seen", "Notes"]
self.series_model.setHorizontalHeaderLabels(self.series_columns)
self.series_table = QTableView()
self.series_table.setFont(font)
self.series_table.setModel(self.series_model)
self.series_table.setVerticalScrollMode(QTableView.ScrollPerPixel)
self.series_table.setMouseTracking(True)
self.series_table.viewport().installEventFilter(self)
self.series_table.hideColumn(0) # Hides the ID column
def load_data(self):
if self.movies_table.isVisible():
self.load_movie_data()
else:
self.load_series_data()
def load_movie_data(self):
self.movies_model.removeRows(0, self.movies_model.rowCount())
movies_data = run_query('SELECT * FROM movies')
if not movies_data:
# Insert a default row if there are no entries in the table
run_query("INSERT INTO movies (movie, year, present, watched, notes) VALUES (?, ?, ?, ?, ?)",
('', '', None, None, ''))
movies_data = run_query('SELECT * FROM movies')
for row in movies_data:
items = [QStandardItem(str(data)) if data is not None else QStandardItem("") for data in row]
self.movies_model.appendRow(items)
def load_series_data(self):
self.series_model.removeRows(0, self.series_model.rowCount())
series_data = run_query('SELECT * FROM series')
if not series_data:
# Insert a default row if there are no entries in the table
run_query("INSERT INTO series (series, seasons, year, present, seasons_present, complete, watched, seasons_seen, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
('', '', '', None, '', None, None, '', ''))
series_data = run_query('SELECT * FROM series')
for row in series_data:
items = [QStandardItem(str(data)) if data is not None else QStandardItem("") for data in row]
self.series_model.appendRow(items)
def show_movies(self):
self.clear_content()
self.content_layout.addWidget(self.movies_table)
self.load_movie_data()
def show_series(self):
self.clear_content()
self.content_layout.addWidget(self.series_table)
self.load_series_data()
def add_entry(self):
if self.movies_table.isVisible():
run_query("INSERT INTO movies (movie, year, present, watched, notes) VALUES (?, ?, ?, ?, ?)",
('', '', None, None, ''))
self.load_movie_data()
elif self.series_table.isVisible():
run_query("INSERT INTO series (series, seasons, year, present, seasons_present, complete, watched, seasons_seen, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
('', '', '', None, '', None, None, '', ''))
self.load_series_data()
def delete_entry(self):
if self.current_row_id is not None:
if self.movies_table.isVisible():
run_query("DELETE FROM movies WHERE id = ?", (self.current_row_id,))
self.load_movie_data()
elif self.series_table.isVisible():
run_query("DELETE FROM series WHERE id = ?", (self.current_row_id,))
self.load_series_data()
def clear_content(self):
# Remove current content
for i in reversed(range(self.content_layout.count())):
widget_to_remove = self.content_layout.itemAt(i).widget()
self.content_layout.removeWidget(widget_to_remove)
if widget_to_remove is not None:
widget_to_remove.setParent(None)
def eventFilter(self, source, event):
if event.type() == QEvent.Type.MouseMove:
table = self.movies_table if self.movies_table.isVisible() else self.series_table
if source is table.viewport():
self.update_buttons_position(table, event.position().toPoint())
return super(MediaTracker, self).eventFilter(source, event)
def update_buttons_position(self, table, pos):
index = table.indexAt(pos)
if index.isValid():
row_index = index.row()
self.current_row_id = table.model().index(row_index, 0).data() # Fetch the ID for the current row
rect = table.visualRect(index)
# Center the buttons vertically within the row
y_pos = rect.top() + (rect.height() - self.plus_button.height()) // 2
# Calculate x-position for centering buttons horizontally within the button bar
button_spacing = 5
button_bar_center = self.button_bar.width() // 2
combined_button_widths = self.plus_button.width() + self.minus_button.width() + button_spacing
first_button_x = button_bar_center - (combined_button_widths // 2)
self.plus_button.move(first_button_x, y_pos)
self.minus_button.move(first_button_x + self.plus_button.width() + button_spacing, y_pos)
self.plus_button.setVisible(True)
self.minus_button.setVisible(True)
else:
self.plus_button.setVisible(False)
self.minus_button.setVisible(False)
self.current_row_id = None
def save_movie_changes(self, start_index, end_index):
for row in range(start_index.row(), end_index.row() + 1):
id_data = self.movies_model.item(row, 0).text()
movie_data = self.movies_model.item(row, 1).text()
year_data = self.movies_model.item(row, 2).text() # Now text
present_data = self.get_bool_value(self.movies_model.item(row, 3))
watched_data = self.get_bool_value(self.movies_model.item(row, 4))
notes_data = self.movies_model.item(row, 5).text()
run_query("UPDATE movies SET movie = ?, year = ?, present = ?, watched = ?, notes = ? WHERE id = ?",
(movie_data, year_data, present_data, watched_data, notes_data, id_data))
def save_series_changes(self, start_index, end_index):
for row in range(start_index.row(), end_index.row() + 1):
id_data = self.series_model.item(row, 0).text()
series_data = self.series_model.item(row, 1).text()
seasons_data = self.series_model.item(row, 2).text()
year_data = self.series_model.item(row, 3).text()
present_data = self.get_bool_value(self.series_model.item(row, 4))
seasons_present_data = self.series_model.item(row, 5).text()
complete_data = self.get_bool_value(self.series_model.item(row, 6))
watched_data = self.get_bool_value(self.series_model.item(row, 7))
seasons_seen_data = self.series_model.item(row, 8).text()
notes_data = self.series_model.item(row, 9).text()
run_query("UPDATE series SET series = ?, seasons = ?, year = ?, present = ?, seasons_present = ?, complete = ?, watched = ?, seasons_seen = ?, notes = ? WHERE id = ?",
(series_data, seasons_data, year_data, present_data, seasons_present_data, complete_data, watched_data, seasons_seen_data, notes_data, id_data))
def get_bool_value(self, item):
text = item.text().lower()
if text in ['true', '1']:
return True
elif text in ['false', '0']:
return False
return None
if __name__ == "__main__":
app = QApplication(sys.argv)
create_tables()
tracker = MediaTracker()
tracker.show()
sys.exit(app.exec())
QFont object is created and configured with a point size of your choice.setFont() method is applied to QPushButton and QTableView widgets to use the defined font throughout the application, ensuring consistent text size. Adjust the setPointSize value as needed for your desired appearance.import sys
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QPushButton, QTableView, QFrame
)
from PySide6.QtGui import QStandardItemModel, QStandardItem, QFont
from PySide6.QtCore import QEvent, Qt
import sqlite3
def run_query(query, parameters=()):
with sqlite3.connect('media.db') as conn:
cursor = conn.cursor()
result = cursor.execute(query, parameters)
if query.strip().lower().startswith("select"):
return result.fetchall()
conn.commit()
def create_tables():
create_movies_table_sql = '''
CREATE TABLE IF NOT EXISTS movies (
id INTEGER PRIMARY KEY AUTOINCREMENT,
movie TEXT,
year TEXT,
present BOOLEAN,
watched BOOLEAN,
notes TEXT
);
'''
create_series_table_sql = '''
CREATE TABLE IF NOT EXISTS series (
id INTEGER PRIMARY KEY AUTOINCREMENT,
series TEXT,
seasons TEXT,
year TEXT,
present BOOLEAN,
seasons_present TEXT,
complete BOOLEAN,
watched BOOLEAN,
seasons_seen TEXT,
notes TEXT
);
'''
run_query(create_movies_table_sql)
run_query(create_series_table_sql)
class MediaTracker(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Movies and Series Tracker")
self.setGeometry(200, 100, 1000, 600)
# Create a QFont instance and set the desired font family and point size
font = QFont()
font.setFamily('Literata') # Set the font family to Literata
font.setPointSize(12) # Adjust font size as desired
self.main_widget = QWidget(self)
self.setCentralWidget(self.main_widget)
self.main_layout = QHBoxLayout(self.main_widget)
# Sidebar with navigation buttons
self.sidebar_layout = QVBoxLayout()
self.main_layout.addLayout(self.sidebar_layout)
self.movies_button = QPushButton("Movies")
self.movies_button.setFont(font)
self.movies_button.clicked.connect(self.show_movies)
self.sidebar_layout.addWidget(self.movies_button)
self.series_button = QPushButton("Series")
self.series_button.setFont(font)
self.series_button.clicked.connect(self.show_series)
self.sidebar_layout.addWidget(self.series_button)
self.sidebar_layout.addStretch()
# Button bar area
self.button_bar = QFrame()
self.button_bar.setFixedWidth(50)
self.button_bar.setStyleSheet("background-color: white;")
self.main_layout.addWidget(self.button_bar)
# Content layout for the table
self.content_layout = QVBoxLayout()
self.main_layout.addLayout(self.content_layout)
self.setup_movie_table(font)
self.setup_series_table(font)
# '+' and '-' buttons for current row
self.plus_button = QPushButton("+", self.button_bar)
self.plus_button.setFont(font)
self.plus_button.setFixedSize(20, 20)
self.plus_button.setVisible(False)
self.plus_button.raise_()
self.plus_button.clicked.connect(self.add_entry)
self.minus_button = QPushButton("-", self.button_bar)
self.minus_button.setFont(font)
self.minus_button.setFixedSize(20, 20)
self.minus_button.setVisible(False)
self.minus_button.raise_()
self.minus_button.clicked.connect(self.delete_entry)
self.current_row_id = None
self.load_data()
self.show_movies()
# Connect model's dataChanged signal to a slot for saving changes
self.movies_model.dataChanged.connect(self.save_movie_changes)
self.series_model.dataChanged.connect(self.save_series_changes)
def setup_movie_table(self, font):
self.movies_model = QStandardItemModel()
self.movies_columns = ["ID", "Movie", "Year", "Present", "Watched", "Notes"]
self.movies_model.setHorizontalHeaderLabels(self.movies_columns)
self.movies_table = QTableView()
self.movies_table.setFont(font)
self.movies_table.setModel(self.movies_model)
self.movies_table.setVerticalScrollMode(QTableView.ScrollPerPixel)
self.movies_table.setMouseTracking(True)
self.movies_table.viewport().installEventFilter(self)
self.movies_table.hideColumn(0) # Hides the ID column
self.content_layout.addWidget(self.movies_table)
def setup_series_table(self, font):
self.series_model = QStandardItemModel()
self.series_columns = ["ID", "Series", "Seasons", "Year", "Present", "Seasons Present",
"Complete", "Watched", "Seasons Seen", "Notes"]
self.series_model.setHorizontalHeaderLabels(self.series_columns)
self.series_table = QTableView()
self.series_table.setFont(font)
self.series_table.setModel(self.series_model)
self.series_table.setVerticalScrollMode(QTableView.ScrollPerPixel)
self.series_table.setMouseTracking(True)
self.series_table.viewport().installEventFilter(self)
self.series_table.hideColumn(0) # Hides the ID column
def load_data(self):
if self.movies_table.isVisible():
self.load_movie_data()
else:
self.load_series_data()
def load_movie_data(self):
self.movies_model.removeRows(0, self.movies_model.rowCount())
movies_data = run_query('SELECT * FROM movies')
if not movies_data:
run_query("INSERT INTO movies (movie, year, present, watched, notes) VALUES (?, ?, ?, ?, ?)",
('', '', None, None, ''))
movies_data = run_query('SELECT * FROM movies')
for row in movies_data:
items = [QStandardItem(str(data)) if data is not None else QStandardItem("") for data in row]
self.movies_model.appendRow(items)
def load_series_data(self):
self.series_model.removeRows(0, self.series_model.rowCount())
series_data = run_query('SELECT * FROM series')
if not series_data:
run_query("INSERT INTO series (series, seasons, year, present, seasons_present, complete, watched, seasons_seen, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
('', '', '', None, '', None, None, '', ''))
series_data = run_query('SELECT * FROM series')
for row in series_data:
items = [QStandardItem(str(data)) if data is not None else QStandardItem("") for data in row]
self.series_model.appendRow(items)
def show_movies(self):
self.clear_content()
self.content_layout.addWidget(self.movies_table)
self.load_movie_data()
def show_series(self):
self.clear_content()
self.content_layout.addWidget(self.series_table)
self.load_series_data()
def add_entry(self):
if self.movies_table.isVisible():
run_query("INSERT INTO movies (movie, year, present, watched, notes) VALUES (?, ?, ?, ?, ?)",
('', '', None, None, ''))
self.load_movie_data()
elif self.series_table.isVisible():
run_query("INSERT INTO series (series, seasons, year, present, seasons_present, complete, watched, seasons_seen, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
('', '', '', None, '', None, None, '', ''))
self.load_series_data()
def delete_entry(self):
if self.current_row_id is not None:
if self.movies_table.isVisible():
run_query("DELETE FROM movies WHERE id = ?", (self.current_row_id,))
self.load_movie_data()
elif self.series_table.isVisible():
run_query("DELETE FROM series WHERE id = ?", (self.current_row_id,))
self.load_series_data()
def clear_content(self):
for i in reversed(range(self.content_layout.count())):
widget_to_remove = self.content_layout.itemAt(i).widget()
self.content_layout.removeWidget(widget_to_remove)
if widget_to_remove is not None:
widget_to_remove.setParent(None)
def eventFilter(self, source, event):
if event.type() == QEvent.Type.MouseMove:
table = self.movies_table if self.movies_table.isVisible() else self.series_table
if source is table.viewport():
self.update_buttons_position(table, event.position().toPoint())
return super(MediaTracker, self).eventFilter(source, event)
def update_buttons_position(self, table, pos):
index = table.indexAt(pos)
if index.isValid():
row_index = index.row()
self.current_row_id = table.model().index(row_index, 0).data()
rect = table.visualRect(index)
y_pos = rect.top() + (rect.height() - self.plus_button.height()) // 2
button_spacing = 5
button_bar_center = self.button_bar.width() // 2
combined_button_widths = self.plus_button.width() + self.minus_button.width() + button_spacing
first_button_x = button_bar_center - (combined_button_widths // 2)
self.plus_button.move(first_button_x, y_pos)
self.minus_button.move(first_button_x + self.plus_button.width() + button_spacing, y_pos)
self.plus_button.setVisible(True)
self.minus_button.setVisible(True)
else:
self.plus_button.setVisible(False)
self.minus_button.setVisible(False)
self.current_row_id = None
def save_movie_changes(self, start_index, end_index):
for row in range(start_index.row(), end_index.row() + 1):
id_data = self.movies_model.item(row, 0).text()
movie_data = self.movies_model.item(row, 1).text()
year_data = self.movies_model.item(row, 2).text()
present_data = self.get_bool_value(self.movies_model.item(row, 3))
watched_data = self.get_bool_value(self.movies_model.item(row, 4))
notes_data = self.movies_model.item(row, 5).text()
run_query("UPDATE movies SET movie = ?, year = ?, present = ?, watched = ?, notes = ? WHERE id = ?",
(movie_data, year_data, present_data, watched_data, notes_data, id_data))
def save_series_changes(self, start_index, end_index):
for row in range(start_index.row(), end_index.row() + 1):
id_data = self.series_model.item(row, 0).text()
series_data = self.series_model.item(row, 1).text()
seasons_data = self.series_model.item(row, 2).text()
year_data = self.series_model.item(row, 3).text()
present_data = self.get_bool_value(self.series_model.item(row, 4))
seasons_present_data = self.series_model.item(row, 5).text()
complete_data = self.get_bool_value(self.series_model.item(row, 6))
watched_data = self.get_bool_value(self.series_model.item(row, 7))
seasons_seen_data = self.series_model.item(row, 8).text()
notes_data = self.series_model.item(row, 9).text()
run_query("UPDATE series SET series = ?, seasons = ?, year = ?, present = ?, seasons_present = ?, complete = ?, watched = ?, seasons_seen = ?, notes = ? WHERE id = ?",
(series_data, seasons_data, year_data, present_data, seasons_present_data, complete_data, watched_data, seasons_seen_data, notes_data, id_data))
def get_bool_value(self, item):
text = item.text().lower()
if text in ['true', '1']:
return True
elif text in ['false', '0']:
return False
return None
if __name__ == "__main__":
app = QApplication(sys.argv)
create_tables()
tracker = MediaTracker()
tracker.show()
sys.exit(app.exec())